text
stringlengths 2.1k
15.6k
|
|---|
def add_sound( self, sound_file: StrPath, time: float | None = None, gain: float | None = None, **kwargs: Any, ) -> None: """This method adds an audio segment from a sound file. Parameters ---------- sound_file The path to the sound file. time The timestamp at which the audio should be added. gain The gain of the given audio segment. **kwargs This method uses add_audio_segment, so any keyword arguments used there can be referenced here. """ file_path = get_full_sound_file_path(sound_file) # we assume files with .wav / .raw suffix are actually # .wav and .raw files, respectively. if file_path.suffix not in (".wav", ".raw"): # we need to pass delete=False to work on Windows # TODO: figure out a way to cache the wav file generated (benchmark needed) with NamedTemporaryFile(suffix=".wav", delete=False) as wav_file_path: convert_audio(file_path, wav_file_path, "pcm_s16le") new_segment = AudioSegment.from_file(wav_file_path.name) logger.info(f"Automatically converted {file_path} to .wav") Path(wav_file_path.name).unlink() else: new_segment = AudioSegment.from_file(file_path) if gain: new_segment = new_segment.apply_gain(gain) self.add_audio_segment(new_segment, time, **kwargs) # Writers def begin_animation( self, allow_write: bool = False, file_path: StrPath | None = None ) -> None: """Used internally by manim to stream the animation to FFMPEG for displaying or writing to a file. Parameters ---------- allow_write Whether or not to write to a video file. """ if write_to_movie() and allow_write: self.open_partial_movie_stream(file_path=file_path) def end_animation(self, allow_write: bool = False) -> None: """Internally used by Manim to stop streaming to FFMPEG gracefully. Parameters ---------- allow_write Whether or not to write to a video file. """ if write_to_movie() and allow_write: self.close_partial_movie_stream() def listen_and_write(self) -> None: """For internal use only: blocks until new frame is available on the queue.""" while True: num_frames, frame_data = self.queue.get() if frame_data is None: break self.encode_and_write_frame(frame_data, num_frames) def encode_and_write_frame(self, frame: PixelArray, num_frames: int) -> None: """For internal use only: takes a given frame in ``np.ndarray`` format and writes it to the stream """ for _ in range(num_frames): # Notes: precomputing reusing packets does not work! # I.e., you cannot do `packets = encode(...)` # and reuse it, as it seems that `mux(...)` # consumes the packet. # The same issue applies for `av_frame`, # reusing it renders weird-looking frames. av_frame = av.VideoFrame.from_ndarray(frame, format="rgba") for packet in self.video_stream.encode(av_frame): self.video_container.mux(packet) def write_frame( self, frame_or_renderer: PixelArray | OpenGLRenderer, num_frames: int = 1 ) -> None: """Used internally by Manim to write a frame to the FFMPEG input buffer. Parameters ---------- frame_or_renderer Pixel array of the frame. num_frames The number of times to write frame. """ if write_to_movie(): if isinstance(frame_or_renderer, np.ndarray): frame = frame_or_renderer else: frame = ( frame_or_renderer.get_frame() if config.renderer == RendererType.OPENGL else frame_or_renderer ) msg = (num_frames, frame) self.queue.put(msg) if is_png_format() and not config["dry_run"]: if isinstance(frame_or_renderer, np.ndarray): image = Image.fromarray(frame_or_renderer) else: image = ( frame_or_renderer.get_image() if config.renderer == RendererType.OPENGL else Image.fromarray(frame_or_renderer) ) target_dir = self.image_file_path.parent / self.image_file_path.stem extension = self.image_file_path.suffix self.output_image( image, target_dir, extension, config["zero_pad"], ) def output_image( self, image: Image.Image, target_dir: StrPath, ext: str, zero_pad: int ) -> None: if zero_pad: image.save(f"{target_dir}{str(self.frame_count).zfill(zero_pad)}{ext}") else: image.save(f"{target_dir}{self.frame_count}{ext}") self.frame_count += 1 def save_image(self, image: Image.Image) -> None: """This method saves the image passed to it in the default image
|
self.image_file_path.stem extension = self.image_file_path.suffix self.output_image( image, target_dir, extension, config["zero_pad"], ) def output_image( self, image: Image.Image, target_dir: StrPath, ext: str, zero_pad: int ) -> None: if zero_pad: image.save(f"{target_dir}{str(self.frame_count).zfill(zero_pad)}{ext}") else: image.save(f"{target_dir}{self.frame_count}{ext}") self.frame_count += 1 def save_image(self, image: Image.Image) -> None: """This method saves the image passed to it in the default image directory. Parameters ---------- image The pixel array of the image to save. """ if config["dry_run"]: return if not config["output_file"]: self.image_file_path = add_version_before_extension(self.image_file_path) image.save(self.image_file_path) self.print_file_ready_message(self.image_file_path) def finish(self) -> None: """Finishes writing to the FFMPEG buffer or writing images to output directory. Combines the partial movie files into the whole scene. If save_last_frame is True, saves the last frame in the default image directory. """ if write_to_movie(): self.combine_to_movie() if config.save_sections: self.combine_to_section_videos() if config["flush_cache"]: self.flush_cache_directory() else: self.clean_cache() elif is_png_format() and not config["dry_run"]: target_dir = self.image_file_path.parent / self.image_file_path.stem logger.info("\n%i images ready at %s\n", self.frame_count, str(target_dir)) if self.subcaptions: self.write_subcaption_file() def open_partial_movie_stream(self, file_path: StrPath | None = None) -> None: """Open a container holding a video stream. This is used internally by Manim initialize the container holding the video stream of a partial movie file. """ if file_path is None: file_path = self.partial_movie_files[self.renderer.num_plays] self.partial_movie_file_path = file_path fps = to_av_frame_rate(config.frame_rate) partial_movie_file_codec = "libx264" partial_movie_file_pix_fmt = "yuv420p" av_options = { "an": "1", # ffmpeg: -an, no audio "crf": "23", # ffmpeg: -crf, constant rate factor (improved bitrate) } if config.movie_file_extension == ".webm": partial_movie_file_codec = "libvpx-vp9" av_options["-auto-alt-ref"] = "1" if config.transparent: partial_movie_file_pix_fmt = "yuva420p" elif config.transparent: partial_movie_file_codec = "qtrle" partial_movie_file_pix_fmt = "argb" with av.open(file_path, mode="w") as video_container: stream = video_container.add_stream( partial_movie_file_codec, rate=fps, options=av_options, ) stream.pix_fmt = partial_movie_file_pix_fmt stream.width = config.pixel_width stream.height = config.pixel_height self.video_container: OutputContainer = video_container self.video_stream: Stream = stream self.queue: Queue[tuple[int, PixelArray | None]] = Queue() self.writer_thread = Thread(target=self.listen_and_write, args=()) self.writer_thread.start() def close_partial_movie_stream(self) -> None: """Close the currently opened video container. Used internally by Manim to first flush the remaining packages in the video stream holding a partial file, and then close the corresponding container. """ self.queue.put((-1, None)) self.writer_thread.join() for packet in self.video_stream.encode(): self.video_container.mux(packet) self.video_container.close() logger.info( f"Animation {self.renderer.num_plays} : Partial movie file written in %(path)s", {"path": f"'{self.partial_movie_file_path}'"}, ) def is_already_cached(self, hash_invocation: str) -> bool: """Will check if a file named with `hash_invocation` exists. Parameters ---------- hash_invocation The hash corresponding to an invocation to either `scene.play` or `scene.wait`. Returns ------- :class:`bool` Whether the file exists. """ if not hasattr(self, "partial_movie_directory") or not write_to_movie(): return False path = ( self.partial_movie_directory / f"{hash_invocation}{config['movie_file_extension']}" ) return path.exists() def combine_files( self, input_files: list[str], output_file: Path, create_gif: bool = False, includes_sound: bool = False, ) -> None: file_list = self.partial_movie_directory / "partial_movie_file_list.txt" logger.debug( f"Partial movie files to combine ({len(input_files)} files): %(p)s", {"p": input_files[:5]}, ) with file_list.open("w", encoding="utf-8") as fp: fp.write("# This file is used internally by FFMPEG.\n") for pf_path in input_files: pf_path = Path(pf_path).as_posix() fp.write(f"file 'file:{pf_path}'\n") av_options = { "safe": "0", # needed to read files } if not includes_sound: av_options["an"] = "1" partial_movies_input = av.open( str(file_list), options=av_options, format="concat" ) partial_movies_stream = partial_movies_input.streams.video[0] output_container = av.open(str(output_file), mode="w") output_container.metadata["comment"] = ( f"Rendered with Manim Community v{__version__}" ) output_stream = output_container.add_stream( codec_name="gif" if create_gif else
|
Path(pf_path).as_posix() fp.write(f"file 'file:{pf_path}'\n") av_options = { "safe": "0", # needed to read files } if not includes_sound: av_options["an"] = "1" partial_movies_input = av.open( str(file_list), options=av_options, format="concat" ) partial_movies_stream = partial_movies_input.streams.video[0] output_container = av.open(str(output_file), mode="w") output_container.metadata["comment"] = ( f"Rendered with Manim Community v{__version__}" ) output_stream = output_container.add_stream( codec_name="gif" if create_gif else None, template=partial_movies_stream if not create_gif else None, ) if config.transparent and config.movie_file_extension == ".webm": output_stream.pix_fmt = "yuva420p" if create_gif: """The following solution was largely inspired from this comment https://github.com/imageio/imageio/issues/995#issuecomment-1580533018, and the following code https://github.com/imageio/imageio/blob/65d79140018bb7c64c0692ea72cb4093e8d632a0/imageio/plugins/pyav.py#L927-L996. """ output_stream.pix_fmt = "rgb8" if config.transparent: output_stream.pix_fmt = "pal8" output_stream.width = config.pixel_width output_stream.height = config.pixel_height output_stream.rate = to_av_frame_rate(config.frame_rate) graph = av.filter.Graph() input_buffer = graph.add_buffer(template=partial_movies_stream) split = graph.add("split") palettegen = graph.add("palettegen", "stats_mode=diff") paletteuse = graph.add( "paletteuse", "dither=bayer:bayer_scale=5:diff_mode=rectangle" ) output_sink = graph.add("buffersink") input_buffer.link_to(split) split.link_to(palettegen, 0, 0) # 1st input of split -> input of palettegen split.link_to(paletteuse, 1, 0) # 2nd output of split -> 1st input palettegen.link_to(paletteuse, 0, 1) # output of palettegen -> 2nd input paletteuse.link_to(output_sink) graph.configure() for frame in partial_movies_input.decode(video=0): graph.push(frame) graph.push(None) # EOF: https://github.com/PyAV-Org/PyAV/issues/886. frames_written = 0 while True: try: frame = graph.pull() if output_stream.codec_context.time_base is not None: frame.time_base = output_stream.codec_context.time_base frame.pts = frames_written frames_written += 1 output_container.mux(output_stream.encode(frame)) except av.error.EOFError: break for packet in output_stream.encode(): output_container.mux(packet) else: for packet in partial_movies_input.demux(partial_movies_stream): # We need to skip the "flushing" packets that `demux` generates. if packet.dts is None: continue packet.dts = None # This seems to be needed, as dts from consecutive # files may not be monotically increasing, so we let libav compute it. # We need to assign the packet to the new stream. packet.stream = output_stream output_container.mux(packet) partial_movies_input.close() output_container.close() def combine_to_movie(self) -> None: """Used internally by Manim to combine the separate partial movie files that make up a Scene into a single video file for that Scene. """ partial_movie_files = [el for el in self.partial_movie_files if el is not None] # NOTE: Here we should do a check and raise an exception if partial # movie file is empty. We can't, as a lot of stuff (in particular, in # tests) use scene initialization, and this error would be raised as # it's just an empty scene initialized. # determine output path movie_file_path = self.movie_file_path if is_gif_format(): movie_file_path = self.gif_file_path if len(partial_movie_files) == 0: # Prevent calling concat on empty list logger.info("No animations are contained in this scene.") return logger.info("Combining to Movie file.") self.combine_files( partial_movie_files, movie_file_path, is_gif_format(), self.includes_sound, ) # handle sound if self.includes_sound and config.format != "gif": sound_file_path = movie_file_path.with_suffix(".wav") # Makes sure sound file length will match video file self.add_audio_segment(AudioSegment.silent(0)) self.audio_segment.export( sound_file_path, format="wav", bitrate="312k", ) # Audio added to a VP9 encoded (webm) video file needs # to be encoded as vorbis or opus. Directly exporting # self.audio_segment with such a codec works in principle, # but tries to call ffmpeg via its CLI -- which we want # to avoid. This is why we need to do the conversion # manually. if config.movie_file_extension == ".webm": ogg_sound_file_path = sound_file_path.with_suffix(".ogg") convert_audio(sound_file_path, ogg_sound_file_path, "libvorbis") sound_file_path = ogg_sound_file_path elif config.movie_file_extension == ".mp4": # Similarly, pyav
|
works in principle, # but tries to call ffmpeg via its CLI -- which we want # to avoid. This is why we need to do the conversion # manually. if config.movie_file_extension == ".webm": ogg_sound_file_path = sound_file_path.with_suffix(".ogg") convert_audio(sound_file_path, ogg_sound_file_path, "libvorbis") sound_file_path = ogg_sound_file_path elif config.movie_file_extension == ".mp4": # Similarly, pyav may reject wav audio in an .mp4 file; # convert to AAC. aac_sound_file_path = sound_file_path.with_suffix(".aac") convert_audio(sound_file_path, aac_sound_file_path, "aac") sound_file_path = aac_sound_file_path temp_file_path = movie_file_path.with_name( f"{movie_file_path.stem}_temp{movie_file_path.suffix}" ) av_options = { "shortest": "1", "metadata": f"comment=Rendered with Manim Community v{__version__}", } with ( av.open(movie_file_path) as video_input, av.open(sound_file_path) as audio_input, ): video_stream = video_input.streams.video[0] audio_stream = audio_input.streams.audio[0] output_container = av.open( str(temp_file_path), mode="w", options=av_options ) output_video_stream = output_container.add_stream(template=video_stream) output_audio_stream = output_container.add_stream(template=audio_stream) for packet in video_input.demux(video_stream): # We need to skip the "flushing" packets that `demux` generates. if packet.dts is None: continue # We need to assign the packet to the new stream. packet.stream = output_video_stream output_container.mux(packet) for packet in audio_input.demux(audio_stream): # We need to skip the "flushing" packets that `demux` generates. if packet.dts is None: continue # We need to assign the packet to the new stream. packet.stream = output_audio_stream output_container.mux(packet) output_container.close() shutil.move(str(temp_file_path), str(movie_file_path)) sound_file_path.unlink() self.print_file_ready_message(str(movie_file_path)) if write_to_movie(): for file_path in partial_movie_files: # We have to modify the accessed time so if we have to clean the cache we remove the one used the longest. modify_atime(file_path) def combine_to_section_videos(self) -> None: """Concatenate partial movie files for each section.""" self.finish_last_section() sections_index: list[dict[str, Any]] = [] for section in self.sections: # only if section does want to be saved if section.video is not None: logger.info(f"Combining partial files for section '{section.name}'") self.combine_files( section.get_clean_partial_movie_files(), self.sections_output_dir / section.video, ) sections_index.append(section.get_dict(self.sections_output_dir)) with (self.sections_output_dir / f"{self.output_name}.json").open("w") as file: json.dump(sections_index, file, indent=4) def clean_cache(self) -> None: """Will clean the cache by removing the oldest partial_movie_files.""" cached_partial_movies = [ (self.partial_movie_directory / file_name) for file_name in self.partial_movie_directory.iterdir() if file_name != "partial_movie_file_list.txt" ] if len(cached_partial_movies) > config["max_files_cached"]: number_files_to_delete = ( len(cached_partial_movies) - config["max_files_cached"] ) oldest_files_to_delete = sorted( cached_partial_movies, key=lambda path: path.stat().st_atime, )[:number_files_to_delete] for file_to_delete in oldest_files_to_delete: file_to_delete.unlink() logger.info( f"The partial movie directory is full (> {config['max_files_cached']} files). Therefore, manim has removed the {number_files_to_delete} oldest file(s)." " You can change this behaviour by changing max_files_cached in config.", ) def flush_cache_directory(self) -> None: """Delete all the cached partial movie files""" cached_partial_movies = [ self.partial_movie_directory / file_name for file_name in self.partial_movie_directory.iterdir() if file_name != "partial_movie_file_list.txt" ] for f in cached_partial_movies: f.unlink() logger.info( f"Cache flushed. {len(cached_partial_movies)} file(s) deleted in %(par_dir)s.", {"par_dir": self.partial_movie_directory}, ) def write_subcaption_file(self) -> None: """Writes the subcaption file.""" if config.output_file is None: return subcaption_file = Path(config.output_file).with_suffix(".srt") subcaption_file.write_text(srt.compose(self.subcaptions), encoding="utf-8") logger.info(f"Subcaption file has been written as {subcaption_file}") def print_file_ready_message(self, file_path: StrPath) -> None: """Prints the "File Ready" message to STDOUT.""" config["output_file"] = file_path logger.info("\nFile ready at %(file_path)s\n", {"file_path": f"'{file_path}'"}) ================================================ FILE: manim/scene/section.py ================================================ """building blocks of segmented video API""" from __future__ import annotations from enum import Enum from pathlib import Path from typing import Any from manim import get_video_metadata __all__ = ["Section", "DefaultSectionType"] class DefaultSectionType(str, Enum): """The type of a section can be used for third party applications. A presentation
|
FILE: manim/scene/section.py ================================================ """building blocks of segmented video API""" from __future__ import annotations from enum import Enum from pathlib import Path from typing import Any from manim import get_video_metadata __all__ = ["Section", "DefaultSectionType"] class DefaultSectionType(str, Enum): """The type of a section can be used for third party applications. A presentation system could for example use the types to created loops. Examples -------- This class can be reimplemented for more types:: class PresentationSectionType(str, Enum): # start, end, wait for continuation by user NORMAL = "presentation.normal" # start, end, immediately continue to next section SKIP = "presentation.skip" # start, end, restart, immediately continue to next section when continued by user LOOP = "presentation.loop" # start, end, restart, finish animation first when user continues COMPLETE_LOOP = "presentation.complete_loop" """ NORMAL = "default.normal" class Section: r"""A :class:`.Scene` can be segmented into multiple Sections. Refer to :doc:`the documentation</tutorials/output_and_config>` for more info. It consists of multiple animations. Attributes ---------- type\_ Can be used by a third party applications to classify different types of sections. video Path to video file with animations belonging to section relative to sections directory. If ``None``, then the section will not be saved. name Human readable, non-unique name for this section. skip_animations Skip rendering the animations in this section when ``True``. partial_movie_files Animations belonging to this section. See Also -------- :class:`.DefaultSectionType` :meth:`.CairoRenderer.update_skipping_status` :meth:`.OpenGLRenderer.update_skipping_status` """ def __init__( self, type_: str, video: str | None, name: str, skip_animations: bool ) -> None: self.type_ = type_ # None when not to be saved -> still keeps section alive self.video: str | None = video self.name = name self.skip_animations = skip_animations self.partial_movie_files: list[str | None] = [] def is_empty(self) -> bool: """Check whether this section is empty. Note that animations represented by ``None`` are also counted. """ return len(self.partial_movie_files) == 0 def get_clean_partial_movie_files(self) -> list[str]: """Return all partial movie files that are not ``None``.""" return [el for el in self.partial_movie_files if el is not None] def get_dict(self, sections_dir: Path) -> dict[str, Any]: """Get dictionary representation with metadata of output video. The output from this function is used from every section to build the sections index file. The output video must have been created in the ``sections_dir`` before executing this method. This is the main part of the Segmented Video API. """ if self.video is None: raise ValueError( f"Section '{self.name}' cannot be exported as dict, it does not have a video path assigned to it" ) video_metadata = get_video_metadata(sections_dir / self.video) return dict( { "name": self.name, "type": self.type_, "video": self.video, }, **video_metadata, ) def __repr__(self) -> str: return f"<Section '{self.name}' stored in '{self.video}'>" ================================================ FILE: manim/scene/three_d_scene.py ================================================ """A scene suitable for rendering three-dimensional objects and animations.""" from __future__ import annotations __all__ = ["ThreeDScene", "SpecialThreeDScene"] import warnings from collections.abc import Iterable, Sequence import numpy as np from manim.mobject.geometry.line import Line from manim.mobject.graphing.coordinate_systems import ThreeDAxes from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.three_d.three_dimensions import Sphere from manim.mobject.value_tracker import ValueTracker from .. import config from ..animation.animation import Animation from ..animation.transform import Transform from ..camera.three_d_camera import ThreeDCamera from ..constants import DEGREES, RendererType from ..mobject.mobject
|
import Iterable, Sequence import numpy as np from manim.mobject.geometry.line import Line from manim.mobject.graphing.coordinate_systems import ThreeDAxes from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.three_d.three_dimensions import Sphere from manim.mobject.value_tracker import ValueTracker from .. import config from ..animation.animation import Animation from ..animation.transform import Transform from ..camera.three_d_camera import ThreeDCamera from ..constants import DEGREES, RendererType from ..mobject.mobject import Mobject from ..mobject.types.vectorized_mobject import VectorizedPoint, VGroup from ..renderer.opengl_renderer import OpenGLCamera from ..scene.scene import Scene from ..utils.config_ops import merge_dicts_recursively class ThreeDScene(Scene): """ This is a Scene, with special configurations and properties that make it suitable for Three Dimensional Scenes. """ def __init__( self, camera_class=ThreeDCamera, ambient_camera_rotation=None, default_angled_camera_orientation_kwargs=None, **kwargs, ): self.ambient_camera_rotation = ambient_camera_rotation if default_angled_camera_orientation_kwargs is None: default_angled_camera_orientation_kwargs = { "phi": 70 * DEGREES, "theta": -135 * DEGREES, } self.default_angled_camera_orientation_kwargs = ( default_angled_camera_orientation_kwargs ) super().__init__(camera_class=camera_class, **kwargs) def set_camera_orientation( self, phi: float | None = None, theta: float | None = None, gamma: float | None = None, zoom: float | None = None, focal_distance: float | None = None, frame_center: Mobject | Sequence[float] | None = None, **kwargs, ): """ This method sets the orientation of the camera in the scene. Parameters ---------- phi The polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians. theta The azimuthal angle i.e the angle that spins the camera around the Z_AXIS. focal_distance The focal_distance of the Camera. gamma The rotation of the camera about the vector from the ORIGIN to the Camera. zoom The zoom factor of the scene. frame_center The new center of the camera frame in cartesian coordinates. """ if phi is not None: self.renderer.camera.set_phi(phi) if theta is not None: self.renderer.camera.set_theta(theta) if focal_distance is not None: self.renderer.camera.set_focal_distance(focal_distance) if gamma is not None: self.renderer.camera.set_gamma(gamma) if zoom is not None: self.renderer.camera.set_zoom(zoom) if frame_center is not None: self.renderer.camera._frame_center.move_to(frame_center) def begin_ambient_camera_rotation(self, rate: float = 0.02, about: str = "theta"): """ This method begins an ambient rotation of the camera about the Z_AXIS, in the anticlockwise direction Parameters ---------- rate The rate at which the camera should rotate about the Z_AXIS. Negative rate means clockwise rotation. about one of 3 options: ["theta", "phi", "gamma"]. defaults to theta. """ # TODO, use a ValueTracker for rate, so that it # can begin and end smoothly about: str = about.lower() try: if config.renderer == RendererType.CAIRO: trackers = { "theta": self.camera.theta_tracker, "phi": self.camera.phi_tracker, "gamma": self.camera.gamma_tracker, } x: ValueTracker = trackers[about] x.add_updater(lambda m, dt: x.increment_value(rate * dt)) self.add(x) elif config.renderer == RendererType.OPENGL: cam: OpenGLCamera = self.camera methods = { "theta": cam.increment_theta, "phi": cam.increment_phi, "gamma": cam.increment_gamma, } cam.add_updater(lambda m, dt: methods[about](rate * dt)) self.add(self.camera) except Exception as e: raise ValueError("Invalid ambient rotation angle.") from e def stop_ambient_camera_rotation(self, about="theta"): """This method stops all ambient camera rotation.""" about: str = about.lower() try: if config.renderer == RendererType.CAIRO: trackers = { "theta": self.camera.theta_tracker, "phi": self.camera.phi_tracker, "gamma": self.camera.gamma_tracker, } x: ValueTracker = trackers[about] x.clear_updaters() self.remove(x) elif config.renderer == RendererType.OPENGL: self.camera.clear_updaters() except Exception as e: raise ValueError("Invalid ambient rotation angle.") from e def begin_3dillusion_camera_rotation( self, rate: float = 1, origin_phi: float | None = None, origin_theta: float | None = None, ): """ This method
|
"phi": self.camera.phi_tracker, "gamma": self.camera.gamma_tracker, } x: ValueTracker = trackers[about] x.clear_updaters() self.remove(x) elif config.renderer == RendererType.OPENGL: self.camera.clear_updaters() except Exception as e: raise ValueError("Invalid ambient rotation angle.") from e def begin_3dillusion_camera_rotation( self, rate: float = 1, origin_phi: float | None = None, origin_theta: float | None = None, ): """ This method creates a 3D camera rotation illusion around the current camera orientation. Parameters ---------- rate The rate at which the camera rotation illusion should operate. origin_phi The polar angle the camera should move around. Defaults to the current phi angle. origin_theta The azimutal angle the camera should move around. Defaults to the current theta angle. """ if origin_theta is None: origin_theta = self.renderer.camera.theta_tracker.get_value() if origin_phi is None: origin_phi = self.renderer.camera.phi_tracker.get_value() val_tracker_theta = ValueTracker(0) def update_theta(m, dt): val_tracker_theta.increment_value(dt * rate) val_for_left_right = 0.2 * np.sin(val_tracker_theta.get_value()) return m.set_value(origin_theta + val_for_left_right) self.renderer.camera.theta_tracker.add_updater(update_theta) self.add(self.renderer.camera.theta_tracker) val_tracker_phi = ValueTracker(0) def update_phi(m, dt): val_tracker_phi.increment_value(dt * rate) val_for_up_down = 0.1 * np.cos(val_tracker_phi.get_value()) - 0.1 return m.set_value(origin_phi + val_for_up_down) self.renderer.camera.phi_tracker.add_updater(update_phi) self.add(self.renderer.camera.phi_tracker) def stop_3dillusion_camera_rotation(self): """This method stops all illusion camera rotations.""" self.renderer.camera.theta_tracker.clear_updaters() self.remove(self.renderer.camera.theta_tracker) self.renderer.camera.phi_tracker.clear_updaters() self.remove(self.renderer.camera.phi_tracker) def move_camera( self, phi: float | None = None, theta: float | None = None, gamma: float | None = None, zoom: float | None = None, focal_distance: float | None = None, frame_center: Mobject | Sequence[float] | None = None, added_anims: Iterable[Animation] = [], **kwargs, ): """ This method animates the movement of the camera to the given spherical coordinates. Parameters ---------- phi The polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians. theta The azimuthal angle i.e the angle that spins the camera around the Z_AXIS. focal_distance The radial focal_distance between ORIGIN and Camera. gamma The rotation of the camera about the vector from the ORIGIN to the Camera. zoom The zoom factor of the camera. frame_center The new center of the camera frame in cartesian coordinates. added_anims Any other animations to be played at the same time. """ anims = [] if config.renderer == RendererType.CAIRO: self.camera: ThreeDCamera value_tracker_pairs = [ (phi, self.camera.phi_tracker), (theta, self.camera.theta_tracker), (focal_distance, self.camera.focal_distance_tracker), (gamma, self.camera.gamma_tracker), (zoom, self.camera.zoom_tracker), ] for value, tracker in value_tracker_pairs: if value is not None: anims.append(tracker.animate.set_value(value)) if frame_center is not None: anims.append(self.camera._frame_center.animate.move_to(frame_center)) elif config.renderer == RendererType.OPENGL: cam: OpenGLCamera = self.camera cam2 = cam.copy() methods = { "theta": cam2.set_theta, "phi": cam2.set_phi, "gamma": cam2.set_gamma, "zoom": cam2.scale, "frame_center": cam2.move_to, } if frame_center is not None: if isinstance(frame_center, OpenGLMobject): frame_center = frame_center.get_center() frame_center = list(frame_center) zoom_value = None if zoom is not None: zoom_value = config.frame_height / (zoom * cam.height) for value, method in [ [theta, "theta"], [phi, "phi"], [gamma, "gamma"], [zoom_value, "zoom"], [frame_center, "frame_center"], ]: if value is not None: methods[method](value) if focal_distance is not None: warnings.warn( "focal distance of OpenGLCamera can not be adjusted.", stacklevel=2, ) anims += [Transform(cam, cam2)] self.play(*anims + added_anims, **kwargs) # These lines are added to improve performance. If manim thinks that frame_center is moving, # it is required to redraw every object. These lines remove frame_center from the Scene once # its animation is done, ensuring that manim does not
|
) anims += [Transform(cam, cam2)] self.play(*anims + added_anims, **kwargs) # These lines are added to improve performance. If manim thinks that frame_center is moving, # it is required to redraw every object. These lines remove frame_center from the Scene once # its animation is done, ensuring that manim does not think that it is moving. Since the # frame_center is never actually drawn, this shouldn't break anything. if frame_center is not None and config.renderer == RendererType.CAIRO: self.remove(self.camera._frame_center) def get_moving_mobjects(self, *animations: Animation): """ This method returns a list of all of the Mobjects in the Scene that are moving, that are also in the animations passed. Parameters ---------- *animations The animations whose mobjects will be checked. """ moving_mobjects = super().get_moving_mobjects(*animations) camera_mobjects = self.renderer.camera.get_value_trackers() + [ self.renderer.camera._frame_center, ] if any(cm in moving_mobjects for cm in camera_mobjects): return self.mobjects return moving_mobjects def add_fixed_orientation_mobjects(self, *mobjects: Mobject, **kwargs): """ This method is used to prevent the rotation and tilting of mobjects as the camera moves around. The mobject can still move in the x,y,z directions, but will always be at the angle (relative to the camera) that it was at when it was passed through this method.) Parameters ---------- *mobjects The Mobject(s) whose orientation must be fixed. **kwargs Some valid kwargs are use_static_center_func : bool center_func : function """ if config.renderer == RendererType.CAIRO: self.add(*mobjects) self.renderer.camera.add_fixed_orientation_mobjects(*mobjects, **kwargs) elif config.renderer == RendererType.OPENGL: for mob in mobjects: mob: OpenGLMobject mob.fix_orientation() self.add(mob) def add_fixed_in_frame_mobjects(self, *mobjects: Mobject): """ This method is used to prevent the rotation and movement of mobjects as the camera moves around. The mobject is essentially overlaid, and is not impacted by the camera's movement in any way. Parameters ---------- *mobjects The Mobjects whose orientation must be fixed. """ if config.renderer == RendererType.CAIRO: self.add(*mobjects) self.camera: ThreeDCamera self.camera.add_fixed_in_frame_mobjects(*mobjects) elif config.renderer == RendererType.OPENGL: for mob in mobjects: mob: OpenGLMobject mob.fix_in_frame() self.add(mob) def remove_fixed_orientation_mobjects(self, *mobjects: Mobject): """ This method "unfixes" the orientation of the mobjects passed, meaning they will no longer be at the same angle relative to the camera. This only makes sense if the mobject was passed through add_fixed_orientation_mobjects first. Parameters ---------- *mobjects The Mobjects whose orientation must be unfixed. """ if config.renderer == RendererType.CAIRO: self.renderer.camera.remove_fixed_orientation_mobjects(*mobjects) elif config.renderer == RendererType.OPENGL: for mob in mobjects: mob: OpenGLMobject mob.unfix_orientation() self.remove(mob) def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject): """ This method undoes what add_fixed_in_frame_mobjects does. It allows the mobject to be affected by the movement of the camera. Parameters ---------- *mobjects The Mobjects whose position and orientation must be unfixed. """ if config.renderer == RendererType.CAIRO: self.renderer.camera.remove_fixed_in_frame_mobjects(*mobjects) elif config.renderer == RendererType.OPENGL: for mob in mobjects: mob: OpenGLMobject mob.unfix_from_frame() self.remove(mob) ## def set_to_default_angled_camera_orientation(self, **kwargs): """ This method sets the default_angled_camera_orientation to the keyword arguments passed, and sets the camera to that orientation. Parameters ---------- **kwargs Some recognised kwargs are phi, theta, focal_distance, gamma, which have the same meaning as the parameters in set_camera_orientation. """ config = dict( self.default_camera_orientation_kwargs, ) # Where doe this come from? config.update(kwargs) self.set_camera_orientation(**config) class SpecialThreeDScene(ThreeDScene): """An extension of :class:`ThreeDScene` with more settings. It has some extra configuration for axes, spheres, and an
|
recognised kwargs are phi, theta, focal_distance, gamma, which have the same meaning as the parameters in set_camera_orientation. """ config = dict( self.default_camera_orientation_kwargs, ) # Where doe this come from? config.update(kwargs) self.set_camera_orientation(**config) class SpecialThreeDScene(ThreeDScene): """An extension of :class:`ThreeDScene` with more settings. It has some extra configuration for axes, spheres, and an override for low quality rendering. Further key differences are: * The camera shades applicable 3DMobjects by default, except if rendering in low quality. * Some default params for Spheres and Axes have been added. """ def __init__( self, cut_axes_at_radius=True, camera_config={"should_apply_shading": True, "exponential_projection": True}, three_d_axes_config={ "num_axis_pieces": 1, "axis_config": { "unit_size": 2, "tick_frequency": 1, "numbers_with_elongated_ticks": [0, 1, 2], "stroke_width": 2, }, }, sphere_config={"radius": 2, "resolution": (24, 48)}, default_angled_camera_position={ "phi": 70 * DEGREES, "theta": -110 * DEGREES, }, # When scene is extracted with -l flag, this # configuration will override the above configuration. low_quality_config={ "camera_config": {"should_apply_shading": False}, "three_d_axes_config": {"num_axis_pieces": 1}, "sphere_config": {"resolution": (12, 24)}, }, **kwargs, ): self.cut_axes_at_radius = cut_axes_at_radius self.camera_config = camera_config self.three_d_axes_config = three_d_axes_config self.sphere_config = sphere_config self.default_angled_camera_position = default_angled_camera_position self.low_quality_config = low_quality_config if self.renderer.camera_config["pixel_width"] == config["pixel_width"]: _config = {} else: _config = self.low_quality_config _config = merge_dicts_recursively(_config, kwargs) super().__init__(**_config) def get_axes(self): """Return a set of 3D axes. Returns ------- :class:`.ThreeDAxes` A set of 3D axes. """ axes = ThreeDAxes(**self.three_d_axes_config) for axis in axes: if self.cut_axes_at_radius: p0 = axis.get_start() p1 = axis.number_to_point(-1) p2 = axis.number_to_point(1) p3 = axis.get_end() new_pieces = VGroup(Line(p0, p1), Line(p1, p2), Line(p2, p3)) for piece in new_pieces: piece.shade_in_3d = True new_pieces.match_style(axis.pieces) axis.pieces.submobjects = new_pieces.submobjects for tick in axis.tick_marks: tick.add(VectorizedPoint(1.5 * tick.get_center())) return axes def get_sphere(self, **kwargs): """ Returns a sphere with the passed keyword arguments as properties. Parameters ---------- **kwargs Any valid parameter of :class:`~.Sphere` or :class:`~.Surface`. Returns ------- :class:`~.Sphere` The sphere object. """ config = merge_dicts_recursively(self.sphere_config, kwargs) return Sphere(**config) def get_default_camera_position(self): """ Returns the default_angled_camera position. Returns ------- dict Dictionary of phi, theta, focal_distance, and gamma. """ return self.default_angled_camera_position def set_camera_to_default_position(self): """Sets the camera to its default position.""" self.set_camera_orientation(**self.default_angled_camera_position) ================================================ FILE: manim/scene/vector_space_scene.py ================================================ """A scene suitable for vector spaces.""" from __future__ import annotations __all__ = ["VectorScene", "LinearTransformationScene"] from collections.abc import Callable, Iterable from typing import TYPE_CHECKING, Any, cast import numpy as np from manim.animation.creation import DrawBorderThenFill, Group from manim.camera.camera import Camera from manim.mobject.geometry.arc import Dot from manim.mobject.geometry.line import Arrow, Line, Vector from manim.mobject.geometry.polygram import Rectangle from manim.mobject.graphing.coordinate_systems import Axes, NumberPlane from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.text.tex_mobject import MathTex, Tex from manim.utils.config_ops import update_dict_recursively from .. import config from ..animation.animation import Animation from ..animation.creation import Create, Write from ..animation.fading import FadeOut from ..animation.growing import GrowArrow from ..animation.transform import ApplyFunction, ApplyPointwiseFunction, Transform from ..constants import * from ..mobject.matrix import Matrix from ..mobject.mobject import Mobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from ..scene.scene import Scene from ..utils.color import ( BLACK, BLUE_D, GREEN_C, GREY, RED_C, WHITE, YELLOW, ManimColor, ParsableManimColor, ) from ..utils.rate_functions import rush_from, rush_into from ..utils.space_ops import angle_of_vector if TYPE_CHECKING: from typing_extensions import Self from manim.typing import ( MappingFunction, Point3D, Point3DLike, Vector2DLike, Vector3D, Vector3DLike, ) X_COLOR = GREEN_C Y_COLOR = RED_C Z_COLOR = BLUE_D # TODO: Much of this scene type
|
GREEN_C, GREY, RED_C, WHITE, YELLOW, ManimColor, ParsableManimColor, ) from ..utils.rate_functions import rush_from, rush_into from ..utils.space_ops import angle_of_vector if TYPE_CHECKING: from typing_extensions import Self from manim.typing import ( MappingFunction, Point3D, Point3DLike, Vector2DLike, Vector3D, Vector3DLike, ) X_COLOR = GREEN_C Y_COLOR = RED_C Z_COLOR = BLUE_D # TODO: Much of this scene type seems dependent on the coordinate system chosen. # That is, being centered at the origin with grid units corresponding to the # arbitrary space units. Change it! # # Also, methods I would have thought of as getters, like coords_to_vector, are # actually doing a lot of animating. class VectorScene(Scene): def __init__(self, basis_vector_stroke_width: float = 6.0, **kwargs: Any) -> None: super().__init__(**kwargs) self.basis_vector_stroke_width = basis_vector_stroke_width def add_plane(self, animate: bool = False, **kwargs: Any) -> NumberPlane: """ Adds a NumberPlane object to the background. Parameters ---------- animate Whether or not to animate the addition of the plane via Create. **kwargs Any valid keyword arguments accepted by NumberPlane. Returns ------- NumberPlane The NumberPlane object. """ plane = NumberPlane(**kwargs) if animate: self.play(Create(plane, lag_ratio=0.5)) self.add(plane) return plane def add_axes( self, animate: bool = False, color: ParsableManimColor | Iterable[ParsableManimColor] = WHITE, ) -> Axes: """ Adds a pair of Axes to the Scene. Parameters ---------- animate Whether or not to animate the addition of the axes through Create. color The color of the axes. Defaults to WHITE. """ axes = Axes(color=color, axis_config={"unit_size": 1}) if animate: self.play(Create(axes)) self.add(axes) return axes def lock_in_faded_grid( self, dimness: float = 0.7, axes_dimness: float = 0.5 ) -> None: """ This method freezes the NumberPlane and Axes that were already in the background, and adds new, manipulatable ones to the foreground. Parameters ---------- dimness The required dimness of the NumberPlane axes_dimness The required dimness of the Axes. """ plane = self.add_plane() axes = plane.get_axes() plane.fade(dimness) axes.set_color(WHITE) axes.fade(axes_dimness) self.add(axes) # TODO # error: Missing positional argument "scene" in call to "update_frame" of "CairoRenderer" [call-arg] self.renderer.update_frame() # type: ignore[call-arg] self.renderer.camera = Camera(self.renderer.get_frame()) self.clear() def get_vector(self, numerical_vector: Vector3DLike, **kwargs: Any) -> Arrow: """ Returns an arrow on the Plane given an input numerical vector. Parameters ---------- numerical_vector The Vector to plot. **kwargs Any valid keyword argument of Arrow. Returns ------- Arrow The Arrow representing the Vector. """ return Arrow( # TODO # error: "VectorScene" has no attribute "plane" [attr-defined] self.plane.coords_to_point(0, 0), # type: ignore[attr-defined] self.plane.coords_to_point(*numerical_vector[:2]), # type: ignore[attr-defined] buff=0, **kwargs, ) def add_vector( self, vector: Arrow | Vector3DLike, color: ParsableManimColor | Iterable[ParsableManimColor] = YELLOW, animate: bool = True, **kwargs: Any, ) -> Arrow: """ Returns the Vector after adding it to the Plane. Parameters ---------- vector It can be a pre-made graphical vector, or the coordinates of one. color The string of the hex color of the vector. This is only taken into consideration if 'vector' is not an Arrow. Defaults to YELLOW. animate Whether or not to animate the addition of the vector by using GrowArrow **kwargs Any valid keyword argument of Arrow. These are only considered if vector is not an Arrow. Returns ------- Arrow The arrow representing the vector. """ if not
|
'vector' is not an Arrow. Defaults to YELLOW. animate Whether or not to animate the addition of the vector by using GrowArrow **kwargs Any valid keyword argument of Arrow. These are only considered if vector is not an Arrow. Returns ------- Arrow The arrow representing the vector. """ if not isinstance(vector, Arrow): vector = Vector(np.asarray(vector), color=color, **kwargs) if animate: self.play(GrowArrow(vector)) self.add(vector) return vector def write_vector_coordinates(self, vector: Vector, **kwargs: Any) -> Matrix: """ Returns a column matrix indicating the vector coordinates, after writing them to the screen. Parameters ---------- vector The arrow representing the vector. **kwargs Any valid keyword arguments of :meth:`~.Vector.coordinate_label`: Returns ------- :class:`.Matrix` The column matrix representing the vector. """ coords: Matrix = vector.coordinate_label(**kwargs) self.play(Write(coords)) return coords def get_basis_vectors( self, i_hat_color: ParsableManimColor | Iterable[ParsableManimColor] = X_COLOR, j_hat_color: ParsableManimColor | Iterable[ParsableManimColor] = Y_COLOR, ) -> VGroup: """ Returns a VGroup of the Basis Vectors (1,0) and (0,1) Parameters ---------- i_hat_color The hex colour to use for the basis vector in the x direction j_hat_color The hex colour to use for the basis vector in the y direction Returns ------- VGroup VGroup of the Vector Mobjects representing the basis vectors. """ return VGroup( *( Vector( np.asarray(vect), color=color, stroke_width=self.basis_vector_stroke_width, ) for vect, color in [([1, 0], i_hat_color), ([0, 1], j_hat_color)] ) ) def get_basis_vector_labels(self, **kwargs: Any) -> VGroup: """ Returns naming labels for the basis vectors. Parameters ---------- **kwargs Any valid keyword arguments of get_vector_label: vector, label (str,MathTex) at_tip (bool=False), direction (str="left"), rotate (bool), color (str), label_scale_factor=VECTOR_LABEL_SCALE_FACTOR (int, float), """ i_hat, j_hat = self.get_basis_vectors() return VGroup( *( self.get_vector_label( vect, label, color=color, label_scale_factor=1, **kwargs ) for vect, label, color in [ (i_hat, "\\hat{\\imath}", X_COLOR), (j_hat, "\\hat{\\jmath}", Y_COLOR), ] ) ) def get_vector_label( self, vector: Vector, label: MathTex | str, at_tip: bool = False, direction: str = "left", rotate: bool = False, color: ParsableManimColor | None = None, label_scale_factor: float = LARGE_BUFF - 0.2, ) -> MathTex: """ Returns naming labels for the passed vector. Parameters ---------- vector Vector Object for which to get the label. at_tip Whether or not to place the label at the tip of the vector. direction If the label should be on the "left" or right of the vector. rotate Whether or not to rotate it to align it with the vector. color The color to give the label. label_scale_factor How much to scale the label by. Returns ------- MathTex The MathTex of the label. """ if not isinstance(label, MathTex): if len(label) == 1: label = "\\vec{\\textbf{%s}}" % label # noqa: UP031 label = MathTex(label) if color is None: prepared_color: ParsableManimColor = vector.get_color() else: prepared_color = color label.set_color(prepared_color) assert isinstance(label, MathTex) label.scale(label_scale_factor) label.add_background_rectangle() if at_tip: vect = vector.get_vector() vect /= np.linalg.norm(vect) label.next_to(vector.get_end(), vect, buff=SMALL_BUFF) else: angle = vector.get_angle() if not rotate: label.rotate(-angle, about_point=ORIGIN) if direction == "left": temp_shift_1: Vector3D = np.asarray(label.get_bottom()) label.shift(-temp_shift_1 + 0.1 * UP) else: temp_shift_2: Vector3D = np.asarray(label.get_top()) label.shift(-temp_shift_2 + 0.1 * DOWN) label.rotate(angle, about_point=ORIGIN) label.shift((vector.get_end() - vector.get_start()) / 2) return label def label_vector( self, vector: Vector, label: MathTex | str, animate: bool = True, **kwargs:
|
not rotate: label.rotate(-angle, about_point=ORIGIN) if direction == "left": temp_shift_1: Vector3D = np.asarray(label.get_bottom()) label.shift(-temp_shift_1 + 0.1 * UP) else: temp_shift_2: Vector3D = np.asarray(label.get_top()) label.shift(-temp_shift_2 + 0.1 * DOWN) label.rotate(angle, about_point=ORIGIN) label.shift((vector.get_end() - vector.get_start()) / 2) return label def label_vector( self, vector: Vector, label: MathTex | str, animate: bool = True, **kwargs: Any ) -> MathTex: """ Shortcut method for creating, and animating the addition of a label for the vector. Parameters ---------- vector The vector for which the label must be added. label The MathTex/string of the label. animate Whether or not to animate the labelling w/ Write **kwargs Any valid keyword argument of get_vector_label Returns ------- :class:`~.MathTex` The MathTex of the label. """ mathtex_label = self.get_vector_label(vector, label, **kwargs) if animate: self.play(Write(mathtex_label, run_time=1)) self.add(mathtex_label) return mathtex_label def position_x_coordinate( self, x_coord: MathTex, x_line: Line, vector: Vector3DLike, ) -> MathTex: # TODO Write DocStrings for this. x_coord.next_to(x_line, -np.sign(vector[1]) * UP) x_coord.set_color(X_COLOR) return x_coord def position_y_coordinate( self, y_coord: MathTex, y_line: Line, vector: Vector3DLike, ) -> MathTex: # TODO Write DocStrings for this. y_coord.next_to(y_line, np.sign(vector[0]) * RIGHT) y_coord.set_color(Y_COLOR) return y_coord def coords_to_vector( self, vector: Vector2DLike, coords_start: Point3DLike = 2 * RIGHT + 2 * UP, clean_up: bool = True, ) -> None: """ This method writes the vector as a column matrix (henceforth called the label), takes the values in it one by one, and form the corresponding lines that make up the x and y components of the vector. Then, an Vector() based vector is created between the lines on the Screen. Parameters ---------- vector The vector to show. coords_start The starting point of the location of the label of the vector that shows it numerically. Defaults to 2 * RIGHT + 2 * UP or (2,2) clean_up Whether or not to remove whatever this method did after it's done. """ starting_mobjects = list(self.mobjects) array = Matrix(vector) array.shift(coords_start) arrow = Vector(vector) x_line = Line(ORIGIN, vector[0] * RIGHT) y_line = Line(x_line.get_end(), arrow.get_end()) x_line.set_color(X_COLOR) y_line.set_color(Y_COLOR) mob_matrix = array.get_mob_matrix() x_coord = mob_matrix[0][0] y_coord = mob_matrix[1][0] self.play(Write(array, run_time=1)) self.wait() self.play( ApplyFunction( lambda x: self.position_x_coordinate(x, x_line, vector), # type: ignore[arg-type] x_coord, ), ) self.play(Create(x_line)) animations = [ ApplyFunction( lambda y: self.position_y_coordinate(y, y_line, vector), # type: ignore[arg-type] y_coord, ), FadeOut(array.get_brackets()), ] self.play(*animations) # TODO: Can we delete the line below? I don't think it have any purpose. # y_coord, _ = (anim.mobject for anim in animations) self.play(Create(y_line)) self.play(Create(arrow)) self.wait() if clean_up: self.clear() self.add(*starting_mobjects) def vector_to_coords( self, vector: Vector3DLike, integer_labels: bool = True, clean_up: bool = True, ) -> tuple[Matrix, Line, Line]: """ This method displays vector as a Vector() based vector, and then shows the corresponding lines that make up the x and y components of the vector. Then, a column matrix (henceforth called the label) is created near the head of the Vector. Parameters ---------- vector The vector to show. integer_labels Whether or not to round the value displayed. in the vector's label to the nearest integer clean_up Whether or not to remove whatever this method did after it's done. """ starting_mobjects = list(self.mobjects) show_creation = False if isinstance(vector,
|
head of the Vector. Parameters ---------- vector The vector to show. integer_labels Whether or not to round the value displayed. in the vector's label to the nearest integer clean_up Whether or not to remove whatever this method did after it's done. """ starting_mobjects = list(self.mobjects) show_creation = False if isinstance(vector, Arrow): arrow = vector vector = arrow.get_end()[:2] else: arrow = Vector(vector) show_creation = True array = arrow.coordinate_label(integer_labels=integer_labels) x_line = Line(ORIGIN, vector[0] * RIGHT) y_line = Line(x_line.get_end(), arrow.get_end()) x_line.set_color(X_COLOR) y_line.set_color(Y_COLOR) x_coord, y_coord = cast(VGroup, array.get_entries()) x_coord_start = self.position_x_coordinate(x_coord.copy(), x_line, vector) y_coord_start = self.position_y_coordinate(y_coord.copy(), y_line, vector) brackets = array.get_brackets() if show_creation: self.play(Create(arrow)) self.play(Create(x_line), Write(x_coord_start), run_time=1) self.play(Create(y_line), Write(y_coord_start), run_time=1) self.wait() self.play( Transform(x_coord_start, x_coord, lag_ratio=0), Transform(y_coord_start, y_coord, lag_ratio=0), Write(brackets, run_time=1), ) self.wait() self.remove(x_coord_start, y_coord_start, brackets) self.add(array) if clean_up: self.clear() self.add(*starting_mobjects) return array, x_line, y_line def show_ghost_movement(self, vector: Arrow | Vector2DLike | Vector3DLike) -> None: """ This method plays an animation that partially shows the entire plane moving in the direction of a particular vector. This is useful when you wish to convey the idea of mentally moving the entire plane in a direction, without actually moving the plane. Parameters ---------- vector The vector which indicates the direction of movement. """ if isinstance(vector, Arrow): vector = vector.get_end() - vector.get_start() else: vector = np.asarray(vector) if len(vector) == 2: vector = np.append(np.array(vector), 0.0) vector_cleaned: Vector3D = vector x_max = int(config["frame_x_radius"] + abs(vector_cleaned[0])) y_max = int(config["frame_y_radius"] + abs(vector_cleaned[1])) # TODO: # I think that this should be a VGroup instead of a VMobject. dots = VMobject( *( # type: ignore[arg-type] Dot(x * RIGHT + y * UP) for x in range(-x_max, x_max) for y in range(-y_max, y_max) ) ) dots.set_fill(BLACK, opacity=0) dots_halfway = dots.copy().shift(vector_cleaned / 2).set_fill(WHITE, 1) dots_end = dots.copy().shift(vector_cleaned) self.play(Transform(dots, dots_halfway, rate_func=rush_into)) self.play(Transform(dots, dots_end, rate_func=rush_from)) self.remove(dots) class LinearTransformationScene(VectorScene): """ This scene contains special methods that make it especially suitable for showing linear transformations. Parameters ---------- include_background_plane Whether or not to include the background plane in the scene. include_foreground_plane Whether or not to include the foreground plane in the scene. background_plane_kwargs Parameters to be passed to :class:`NumberPlane` to adjust the background plane. foreground_plane_kwargs Parameters to be passed to :class:`NumberPlane` to adjust the foreground plane. show_coordinates Whether or not to include the coordinates for the background plane. show_basis_vectors Whether to show the basis x_axis -> ``i_hat`` and y_axis -> ``j_hat`` vectors. basis_vector_stroke_width The ``stroke_width`` of the basis vectors. i_hat_color The color of the ``i_hat`` vector. j_hat_color The color of the ``j_hat`` vector. leave_ghost_vectors Indicates the previous position of the basis vectors following a transformation. Examples ------- .. manim:: LinearTransformationSceneExample class LinearTransformationSceneExample(LinearTransformationScene): def __init__(self, **kwargs): LinearTransformationScene.__init__( self, show_coordinates=True, leave_ghost_vectors=True, **kwargs ) def construct(self): matrix = [[1, 1], [0, 1]] self.apply_matrix(matrix) self.wait() """ def __init__( self, include_background_plane: bool = True, include_foreground_plane: bool = True, background_plane_kwargs: dict[str, Any] | None = None, foreground_plane_kwargs: dict[str, Any] | None = None, show_coordinates: bool = False, show_basis_vectors: bool = True, basis_vector_stroke_width: float = 6, i_hat_color: ParsableManimColor = X_COLOR, j_hat_color: ParsableManimColor = Y_COLOR, leave_ghost_vectors: bool = False, **kwargs: Any, ) -> None: super().__init__(**kwargs) self.include_background_plane = include_background_plane
|
bool = True, background_plane_kwargs: dict[str, Any] | None = None, foreground_plane_kwargs: dict[str, Any] | None = None, show_coordinates: bool = False, show_basis_vectors: bool = True, basis_vector_stroke_width: float = 6, i_hat_color: ParsableManimColor = X_COLOR, j_hat_color: ParsableManimColor = Y_COLOR, leave_ghost_vectors: bool = False, **kwargs: Any, ) -> None: super().__init__(**kwargs) self.include_background_plane = include_background_plane self.include_foreground_plane = include_foreground_plane self.show_coordinates = show_coordinates self.show_basis_vectors = show_basis_vectors self.basis_vector_stroke_width = basis_vector_stroke_width self.i_hat_color = ManimColor(i_hat_color) self.j_hat_color = ManimColor(j_hat_color) self.leave_ghost_vectors = leave_ghost_vectors self.background_plane_kwargs: dict[str, Any] = { "color": GREY, "axis_config": { "color": GREY, }, "background_line_style": { "stroke_color": GREY, "stroke_width": 1, }, } self.ghost_vectors = VGroup() self.foreground_plane_kwargs: dict[str, Any] = { "x_range": np.array([-config["frame_width"], config["frame_width"], 1.0]), "y_range": np.array([-config["frame_width"], config["frame_width"], 1.0]), "faded_line_ratio": 1, } self.update_default_configs( (self.foreground_plane_kwargs, self.background_plane_kwargs), (foreground_plane_kwargs, background_plane_kwargs), ) @staticmethod def update_default_configs( default_configs: Iterable[dict[str, Any]], passed_configs: Iterable[dict[str, Any] | None], ) -> None: for default_config, passed_config in zip(default_configs, passed_configs): if passed_config is not None: update_dict_recursively(default_config, passed_config) def setup(self) -> None: # The has_already_setup attr is to not break all the old Scenes if hasattr(self, "has_already_setup"): return self.has_already_setup = True self.background_mobjects: list[Mobject] = [] self.foreground_mobjects: list[Mobject] = [] self.transformable_mobjects: list[Mobject] = [] self.moving_vectors: list[Mobject] = [] self.transformable_labels: list[MathTex] = [] self.moving_mobjects: list[Mobject] = [] self.background_plane = NumberPlane(**self.background_plane_kwargs) if self.show_coordinates: self.background_plane.add_coordinates() if self.include_background_plane: self.add_background_mobject(self.background_plane) if self.include_foreground_plane: self.plane = NumberPlane(**self.foreground_plane_kwargs) self.add_transformable_mobject(self.plane) if self.show_basis_vectors: self.basis_vectors = self.get_basis_vectors( i_hat_color=self.i_hat_color, j_hat_color=self.j_hat_color, ) self.moving_vectors += list(self.basis_vectors) self.i_hat, self.j_hat = self.basis_vectors self.add(self.basis_vectors) def add_special_mobjects( self, mob_list: list[Mobject], *mobs_to_add: Mobject ) -> None: """ Adds mobjects to a separate list that can be tracked, if these mobjects have some extra importance. Parameters ---------- mob_list The special list to which you want to add these mobjects. *mobs_to_add The mobjects to add. """ for mobject in mobs_to_add: if mobject not in mob_list: mob_list.append(mobject) self.add(mobject) def add_background_mobject(self, *mobjects: Mobject) -> None: """ Adds the mobjects to the special list self.background_mobjects. Parameters ---------- *mobjects The mobjects to add to the list. """ self.add_special_mobjects(self.background_mobjects, *mobjects) # TODO, this conflicts with Scene.add_foreground_mobject # Please be aware that there is also the method Scene.add_foreground_mobjects. def add_foreground_mobject(self, *mobjects: Mobject) -> None: # type: ignore[override] """ Adds the mobjects to the special list self.foreground_mobjects. Parameters ---------- *mobjects The mobjects to add to the list """ self.add_special_mobjects(self.foreground_mobjects, *mobjects) def add_transformable_mobject(self, *mobjects: Mobject) -> None: """ Adds the mobjects to the special list self.transformable_mobjects. Parameters ---------- *mobjects The mobjects to add to the list. """ self.add_special_mobjects(self.transformable_mobjects, *mobjects) def add_moving_mobject( self, mobject: Mobject, target_mobject: Mobject | None = None ) -> None: """ Adds the mobject to the special list self.moving_mobject, and adds a property to the mobject called mobject.target, which keeps track of what the mobject will move to or become etc. Parameters ---------- mobject The mobjects to add to the list target_mobject What the moving_mobject goes to, etc. """ mobject.target = target_mobject self.add_special_mobjects(self.moving_mobjects, mobject) def get_ghost_vectors(self) -> VGroup: """ Returns all ghost vectors ever added to ``self``. Each element is a ``VGroup`` of two ghost vectors. """ return self.ghost_vectors def get_unit_square( self, color: ParsableManimColor | Iterable[ParsableManimColor] = YELLOW, opacity: float = 0.3, stroke_width: float = 3, ) -> Rectangle: """ Returns a
|
self.add_special_mobjects(self.moving_mobjects, mobject) def get_ghost_vectors(self) -> VGroup: """ Returns all ghost vectors ever added to ``self``. Each element is a ``VGroup`` of two ghost vectors. """ return self.ghost_vectors def get_unit_square( self, color: ParsableManimColor | Iterable[ParsableManimColor] = YELLOW, opacity: float = 0.3, stroke_width: float = 3, ) -> Rectangle: """ Returns a unit square for the current NumberPlane. Parameters ---------- color The string of the hex color code of the color wanted. opacity The opacity of the square stroke_width The stroke_width in pixels of the border of the square Returns ------- Square """ square = self.square = Rectangle( color=color, width=self.plane.get_x_unit_size(), height=self.plane.get_y_unit_size(), stroke_color=color, stroke_width=stroke_width, fill_color=color, fill_opacity=opacity, ) square.move_to(self.plane.coords_to_point(0, 0), DL) return square def add_unit_square(self, animate: bool = False, **kwargs: Any) -> Self: """ Adds a unit square to the scene via self.get_unit_square. Parameters ---------- animate Whether or not to animate the addition with DrawBorderThenFill. **kwargs Any valid keyword arguments of self.get_unit_square() Returns ------- Square The unit square. """ square = self.get_unit_square(**kwargs) if animate: self.play( DrawBorderThenFill(square), Animation(Group(*self.moving_vectors)), ) self.add_transformable_mobject(square) self.bring_to_front(*self.moving_vectors) self.square = square return self def add_vector( self, vector: Arrow | list | tuple | np.ndarray, color: ParsableManimColor = YELLOW, animate: bool = False, **kwargs: Any, ) -> Arrow: """ Adds a vector to the scene, and puts it in the special list self.moving_vectors. Parameters ---------- vector It can be a pre-made graphical vector, or the coordinates of one. color The string of the hex color of the vector. This is only taken into consideration if 'vector' is not an Arrow. Defaults to YELLOW. **kwargs Any valid keyword argument of VectorScene.add_vector. Returns ------- Arrow The arrow representing the vector. """ vector = super().add_vector(vector, color=color, animate=animate, **kwargs) self.moving_vectors.append(vector) return vector def write_vector_coordinates(self, vector: Vector, **kwargs: Any) -> Matrix: """ Returns a column matrix indicating the vector coordinates, after writing them to the screen, and adding them to the special list self.foreground_mobjects Parameters ---------- vector The arrow representing the vector. **kwargs Any valid keyword arguments of VectorScene.write_vector_coordinates Returns ------- Matrix The column matrix representing the vector. """ coords = super().write_vector_coordinates(vector, **kwargs) self.add_foreground_mobject(coords) return coords def add_transformable_label( self, vector: Vector, label: MathTex | str, transformation_name: str | MathTex = "L", new_label: str | MathTex | None = None, **kwargs: Any, ) -> MathTex: """ Method for creating, and animating the addition of a transformable label for the vector. Parameters ---------- vector The vector for which the label must be added. label The MathTex/string of the label. transformation_name The name to give the transformation as a label. new_label What the label should display after a Linear Transformation **kwargs Any valid keyword argument of get_vector_label Returns ------- :class:`~.MathTex` The MathTex of the label. """ # TODO: Clear up types in this function. This is currently a mess. label_mob = self.label_vector(vector, label, **kwargs) if new_label: label_mob.target_text = new_label # type: ignore[attr-defined] else: label_mob.target_text = ( # type: ignore[attr-defined] f"{transformation_name}({label_mob.get_tex_string()})" ) label_mob.vector = vector # type: ignore[attr-defined] label_mob.kwargs = kwargs # type: ignore[attr-defined] if "animate" in label_mob.kwargs: # type: ignore[operator] label_mob.kwargs.pop("animate") # type: ignore[attr-defined] self.transformable_labels.append(label_mob) return cast(MathTex, label_mob) def add_title( self,
|
self.label_vector(vector, label, **kwargs) if new_label: label_mob.target_text = new_label # type: ignore[attr-defined] else: label_mob.target_text = ( # type: ignore[attr-defined] f"{transformation_name}({label_mob.get_tex_string()})" ) label_mob.vector = vector # type: ignore[attr-defined] label_mob.kwargs = kwargs # type: ignore[attr-defined] if "animate" in label_mob.kwargs: # type: ignore[operator] label_mob.kwargs.pop("animate") # type: ignore[attr-defined] self.transformable_labels.append(label_mob) return cast(MathTex, label_mob) def add_title( self, title: str | MathTex | Tex, scale_factor: float = 1.5, animate: bool = False, ) -> Self: """ Adds a title, after scaling it, adding a background rectangle, moving it to the top and adding it to foreground_mobjects adding it as a local variable of self. Returns the Scene. Parameters ---------- title What the title should be. scale_factor How much the title should be scaled by. animate Whether or not to animate the addition. Returns ------- LinearTransformationScene The scene with the title added to it. """ if not isinstance(title, (Mobject, OpenGLMobject)): title = Tex(title).scale(scale_factor) title.to_edge(UP) title.add_background_rectangle() if animate: self.play(Write(title)) self.add_foreground_mobject(title) self.title = title return self def get_matrix_transformation( self, matrix: np.ndarray | list | tuple ) -> Callable[[Point3D], Point3D]: """ Returns a function corresponding to the linear transformation represented by the matrix passed. Parameters ---------- matrix The matrix. """ return self.get_transposed_matrix_transformation(np.array(matrix).T) def get_transposed_matrix_transformation( self, transposed_matrix: np.ndarray | list | tuple ) -> Callable[[Point3D], Point3D]: """ Returns a function corresponding to the linear transformation represented by the transposed matrix passed. Parameters ---------- transposed_matrix The matrix. """ transposed_matrix = np.array(transposed_matrix) if transposed_matrix.shape == (2, 2): new_matrix = np.identity(3) new_matrix[:2, :2] = transposed_matrix transposed_matrix = new_matrix elif transposed_matrix.shape != (3, 3): raise ValueError("Matrix has bad dimensions") return lambda point: np.dot(point, transposed_matrix) def get_piece_movement(self, pieces: Iterable[Mobject]) -> Transform: """ This method returns an animation that moves an arbitrary mobject in "pieces" to its corresponding .target value. If self.leave_ghost_vectors is True, ghosts of the original positions/mobjects are left on screen Parameters ---------- pieces The pieces for which the movement must be shown. Returns ------- Animation The animation of the movement. """ v_pieces = [piece for piece in pieces if isinstance(piece, VMobject)] start = VGroup(*v_pieces) target = VGroup(*(mob.target for mob in v_pieces)) # don't add empty VGroups if self.leave_ghost_vectors and start.submobjects: # start.copy() gives a VGroup of Vectors self.ghost_vectors.add(start.copy().fade(0.7)) self.add(self.ghost_vectors[-1]) return Transform(start, target, lag_ratio=0) def get_moving_mobject_movement(self, func: MappingFunction) -> Transform: """ This method returns an animation that moves a mobject in "self.moving_mobjects" to its corresponding .target value. func is a function that determines where the .target goes. Parameters ---------- func The function that determines where the .target of the moving mobject goes. Returns ------- Animation The animation of the movement. """ for m in self.moving_mobjects: if m.target is None: m.target = m.copy() temp: Point3D = m.get_center() target_point = func(temp) m.target.move_to(target_point) return self.get_piece_movement(self.moving_mobjects) def get_vector_movement(self, func: MappingFunction) -> Transform: """ This method returns an animation that moves a mobject in "self.moving_vectors" to its corresponding .target value. func is a function that determines where the .target goes. Parameters ---------- func The function that determines where the .target of the moving mobject goes. Returns ------- Animation The animation of the movement. """ for v in self.moving_vectors: v.target = Vector(func(v.get_end()), color=v.get_color())
|
mobject in "self.moving_vectors" to its corresponding .target value. func is a function that determines where the .target goes. Parameters ---------- func The function that determines where the .target of the moving mobject goes. Returns ------- Animation The animation of the movement. """ for v in self.moving_vectors: v.target = Vector(func(v.get_end()), color=v.get_color()) norm = float(np.linalg.norm(v.target.get_end())) if norm < 0.1: v.target.get_tip().scale(norm) return self.get_piece_movement(self.moving_vectors) def get_transformable_label_movement(self) -> Transform: """ This method returns an animation that moves all labels in "self.transformable_labels" to its corresponding .target . Returns ------- Animation The animation of the movement. """ for label in self.transformable_labels: # TODO: This location and lines 933 and 335 are the only locations in # the code where the target_text property is referenced. target_text: MathTex | str = label.target_text # type: ignore[assignment] label.target = self.get_vector_label( label.vector.target, # type: ignore[attr-defined] target_text, **label.kwargs, # type: ignore[arg-type] ) return self.get_piece_movement(self.transformable_labels) def apply_matrix(self, matrix: np.ndarray | list | tuple, **kwargs: Any) -> None: """ Applies the transformation represented by the given matrix to the number plane, and each vector/similar mobject on it. Parameters ---------- matrix The matrix. **kwargs Any valid keyword argument of self.apply_transposed_matrix() """ self.apply_transposed_matrix(np.array(matrix).T, **kwargs) def apply_inverse(self, matrix: np.ndarray | list | tuple, **kwargs: Any) -> None: """ This method applies the linear transformation represented by the inverse of the passed matrix to the number plane, and each vector/similar mobject on it. Parameters ---------- matrix The matrix whose inverse is to be applied. **kwargs Any valid keyword argument of self.apply_matrix() """ self.apply_matrix(np.linalg.inv(matrix), **kwargs) def apply_transposed_matrix( self, transposed_matrix: np.ndarray | list | tuple, **kwargs: Any ) -> None: """ Applies the transformation represented by the given transposed matrix to the number plane, and each vector/similar mobject on it. Parameters ---------- transposed_matrix The matrix. **kwargs Any valid keyword argument of self.apply_function() """ func = self.get_transposed_matrix_transformation(transposed_matrix) if "path_arc" not in kwargs: net_rotation = np.mean( [angle_of_vector(func(RIGHT)), angle_of_vector(func(UP)) - np.pi / 2], ) kwargs["path_arc"] = net_rotation self.apply_function(func, **kwargs) def apply_inverse_transpose( self, t_matrix: np.ndarray | list | tuple, **kwargs: Any ) -> None: """ Applies the inverse of the transformation represented by the given transposed matrix to the number plane and each vector/similar mobject on it. Parameters ---------- t_matrix The matrix. **kwargs Any valid keyword argument of self.apply_transposed_matrix() """ t_inv = np.linalg.inv(np.array(t_matrix).T).T self.apply_transposed_matrix(t_inv, **kwargs) def apply_nonlinear_transformation( self, function: Callable[[np.ndarray], np.ndarray], **kwargs: Any ) -> None: """ Applies the non-linear transformation represented by the given function to the number plane and each vector/similar mobject on it. Parameters ---------- function The function. **kwargs Any valid keyword argument of self.apply_function() """ self.plane.prepare_for_nonlinear_transform() self.apply_function(function, **kwargs) def apply_function( self, function: MappingFunction, added_anims: list[Animation] = [], **kwargs: Any, ) -> None: """ Applies the given function to each of the mobjects in self.transformable_mobjects, and plays the animation showing this. Parameters ---------- function The function that affects each point of each mobject in self.transformable_mobjects. added_anims Any other animations that need to be played simultaneously with this. **kwargs Any valid keyword argument of a self.play() call. """ if "run_time" not in kwargs: kwargs["run_time"] = 3 anims = ( [ ApplyPointwiseFunction(function, t_mob) #
|
---------- function The function that affects each point of each mobject in self.transformable_mobjects. added_anims Any other animations that need to be played simultaneously with this. **kwargs Any valid keyword argument of a self.play() call. """ if "run_time" not in kwargs: kwargs["run_time"] = 3 anims = ( [ ApplyPointwiseFunction(function, t_mob) # type: ignore[arg-type] for t_mob in self.transformable_mobjects ] + [ self.get_vector_movement(function), self.get_transformable_label_movement(), self.get_moving_mobject_movement(function), ] + [Animation(f_mob) for f_mob in self.foreground_mobjects] + added_anims ) self.play(*anims, **kwargs) ================================================ FILE: manim/scene/zoomed_scene.py ================================================ """A scene supporting zooming in on a specified section. Examples -------- .. manim:: UseZoomedScene class UseZoomedScene(ZoomedScene): def construct(self): dot = Dot().set_color(GREEN) self.add(dot) self.wait(1) self.activate_zooming(animate=False) self.wait(1) self.play(dot.animate.shift(LEFT)) .. manim:: ChangingZoomScale class ChangingZoomScale(ZoomedScene): def __init__(self, **kwargs): ZoomedScene.__init__( self, zoom_factor=0.3, zoomed_display_height=1, zoomed_display_width=3, image_frame_stroke_width=20, zoomed_camera_config={ "default_frame_stroke_width": 3, }, **kwargs ) def construct(self): dot = Dot().set_color(GREEN) sq = Circle(fill_opacity=1, radius=0.2).next_to(dot, RIGHT) self.add(dot, sq) self.wait(1) self.activate_zooming(animate=False) self.wait(1) self.play(dot.animate.shift(LEFT * 0.3)) self.play(self.zoomed_camera.frame.animate.scale(4)) self.play(self.zoomed_camera.frame.animate.shift(0.5 * DOWN)) """ from __future__ import annotations __all__ = ["ZoomedScene"] from typing import TYPE_CHECKING, Any from ..animation.transform import ApplyMethod from ..camera.camera import Camera from ..camera.moving_camera import MovingCamera from ..camera.multi_camera import MultiCamera from ..constants import * from ..mobject.types.image_mobject import ImageMobjectFromCamera from ..renderer.opengl_renderer import OpenGLCamera from ..scene.moving_camera_scene import MovingCameraScene if TYPE_CHECKING: from manim.typing import Point3DLike, Vector3D # Note, any scenes from old videos using ZoomedScene will almost certainly # break, as it was restructured. class ZoomedScene(MovingCameraScene): """This is a Scene with special configurations made for when a particular part of the scene must be zoomed in on and displayed separately. """ def __init__( self, camera_class: type[Camera] = MultiCamera, zoomed_display_height: float = 3, zoomed_display_width: float = 3, zoomed_display_center: Point3DLike | None = None, zoomed_display_corner: Vector3D = UP + RIGHT, zoomed_display_corner_buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER, zoomed_camera_config: dict[str, Any] = { "default_frame_stroke_width": 2, "background_opacity": 1, }, zoomed_camera_image_mobject_config: dict[str, Any] = {}, zoomed_camera_frame_starting_position: Point3DLike = ORIGIN, zoom_factor: float = 0.15, image_frame_stroke_width: float = 3, zoom_activated: bool = False, **kwargs: Any, ) -> None: self.zoomed_display_height = zoomed_display_height self.zoomed_display_width = zoomed_display_width self.zoomed_display_center = zoomed_display_center self.zoomed_display_corner = zoomed_display_corner self.zoomed_display_corner_buff = zoomed_display_corner_buff self.zoomed_camera_config = zoomed_camera_config self.zoomed_camera_image_mobject_config = zoomed_camera_image_mobject_config self.zoomed_camera_frame_starting_position = ( zoomed_camera_frame_starting_position ) self.zoom_factor = zoom_factor self.image_frame_stroke_width = image_frame_stroke_width self.zoom_activated = zoom_activated super().__init__(camera_class=camera_class, **kwargs) def setup(self) -> None: """This method is used internally by Manim to setup the scene for proper use. """ super().setup() # Initialize camera and display zoomed_camera = MovingCamera(**self.zoomed_camera_config) zoomed_display = ImageMobjectFromCamera( zoomed_camera, **self.zoomed_camera_image_mobject_config ) zoomed_display.add_display_frame() for mob in zoomed_camera.frame, zoomed_display: mob.stretch_to_fit_height(self.zoomed_display_height) mob.stretch_to_fit_width(self.zoomed_display_width) zoomed_camera.frame.scale(self.zoom_factor) # Position camera and display zoomed_camera.frame.move_to(self.zoomed_camera_frame_starting_position) if self.zoomed_display_center is not None: zoomed_display.move_to(self.zoomed_display_center) else: zoomed_display.to_corner( self.zoomed_display_corner, buff=self.zoomed_display_corner_buff, ) self.zoomed_camera = zoomed_camera self.zoomed_display = zoomed_display def activate_zooming(self, animate: bool = False) -> None: """This method is used to activate the zooming for the zoomed_camera. Parameters ---------- animate Whether or not to animate the activation of the zoomed camera. """ self.zoom_activated = True self.renderer.camera.add_image_mobject_from_camera(self.zoomed_display) # type: ignore[union-attr] if animate: self.play(self.get_zoom_in_animation()) self.play(self.get_zoomed_display_pop_out_animation()) self.add_foreground_mobjects( self.zoomed_camera.frame, self.zoomed_display, ) def get_zoom_in_animation(self, run_time: float = 2, **kwargs: Any) -> ApplyMethod: """Returns the animation of camera zooming in. Parameters ---------- run_time The run_time of the animation of the camera zooming in. **kwargs Any valid keyword arguments of ApplyMethod() Returns
|
self.renderer.camera.add_image_mobject_from_camera(self.zoomed_display) # type: ignore[union-attr] if animate: self.play(self.get_zoom_in_animation()) self.play(self.get_zoomed_display_pop_out_animation()) self.add_foreground_mobjects( self.zoomed_camera.frame, self.zoomed_display, ) def get_zoom_in_animation(self, run_time: float = 2, **kwargs: Any) -> ApplyMethod: """Returns the animation of camera zooming in. Parameters ---------- run_time The run_time of the animation of the camera zooming in. **kwargs Any valid keyword arguments of ApplyMethod() Returns ------- ApplyMethod The animation of the camera zooming in. """ frame = self.zoomed_camera.frame if isinstance(self.camera, OpenGLCamera): full_frame_width, full_frame_height = self.camera.frame_shape else: full_frame_height = self.camera.frame_height full_frame_width = self.camera.frame_width frame.save_state() frame.stretch_to_fit_width(full_frame_width) frame.stretch_to_fit_height(full_frame_height) frame.center() frame.set_stroke(width=0) return ApplyMethod(frame.restore, run_time=run_time, **kwargs) def get_zoomed_display_pop_out_animation(self, **kwargs: Any) -> ApplyMethod: """This is the animation of the popping out of the mini-display that shows the content of the zoomed camera. Returns ------- ApplyMethod The Animation of the Zoomed Display popping out. """ display = self.zoomed_display display.save_state() display.replace(self.zoomed_camera.frame, stretch=True) return ApplyMethod(display.restore) def get_zoom_factor(self) -> float: """Returns the Zoom factor of the Zoomed camera. Defined as the ratio between the height of the zoomed camera and the height of the zoomed mini display. Returns ------- float The zoom factor. """ zoom_factor: float = ( self.zoomed_camera.frame.height / self.zoomed_display.height ) return zoom_factor ================================================ FILE: manim/templates/Axes.mtp ================================================ class AxesTemplate(Scene): def construct(self): graph = Axes( x_range=[-1,10,1], y_range=[-1,10,1], x_length=9, y_length=6, axis_config={"include_tip":False} ) labels = graph.get_axis_labels() self.add(graph, labels) ================================================ FILE: manim/templates/Default.mtp ================================================ class DefaultTemplate(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set color and transparency square = Square() # create a square square.flip(RIGHT) # flip horizontally square.rotate(-3 * TAU / 8) # rotate a certain amount self.play(Create(square)) # animate the creation of the square self.play(Transform(square, circle)) # interpolate the square into the circle self.play(FadeOut(square)) # fade out animation ================================================ FILE: manim/templates/MovingCamera.mtp ================================================ class MovingCameraTemplate(MovingCameraScene): def construct(self): text = Text("Hello World").set_color(BLUE) self.add(text) self.camera.frame.save_state() self.play(self.camera.frame.animate.set(width=text.width * 1.2)) self.wait(0.3) self.play(Restore(self.camera.frame)) ================================================ FILE: manim/templates/template.cfg ================================================ [CLI] frame_rate = 30 pixel_height = 480 pixel_width = 854 background_color = BLACK background_opacity = 1 scene_names = DefaultScene ================================================ FILE: manim/utils/__init__.py ================================================ [Empty file] ================================================ FILE: manim/utils/caching.py ================================================ from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING, Any from .. import config, logger from ..utils.hashing import get_hash_from_play_call __all__ = ["handle_caching_play"] if TYPE_CHECKING: from manim.renderer.opengl_renderer import OpenGLRenderer from manim.scene.scene import Scene def handle_caching_play(func: Callable[..., None]) -> Callable[..., None]: """Decorator that returns a wrapped version of func that will compute the hash of the play invocation. The returned function will act according to the computed hash: either skip the animation because it's already cached, or let the invoked function play normally. Parameters ---------- func The play like function that has to be written to the video file stream. Take the same parameters as `scene.play`. """ # NOTE : This is only kept for OpenGL renderer. # The play logic of the cairo renderer as been refactored and does not need this function anymore. # When OpenGL renderer will have a proper testing system, # the play logic of the latter has to be refactored in the same way the cairo renderer has been, and thus this # method has to be deleted. def wrapper(self: OpenGLRenderer, scene: Scene, *args: Any,
|
need this function anymore. # When OpenGL renderer will have a proper testing system, # the play logic of the latter has to be refactored in the same way the cairo renderer has been, and thus this # method has to be deleted. def wrapper(self: OpenGLRenderer, scene: Scene, *args: Any, **kwargs: Any) -> None: self.skip_animations = self._original_skipping_status self.update_skipping_status() animations = scene.compile_animations(*args, **kwargs) scene.add_mobjects_from_animations(animations) if self.skip_animations: logger.debug(f"Skipping animation {self.num_plays}") func(self, scene, *args, **kwargs) # If the animation is skipped, we mark its hash as None. # When sceneFileWriter will start combining partial movie files, it won't take into account None hashes. self.animations_hashes.append(None) self.file_writer.add_partial_movie_file(None) return if not config["disable_caching"]: mobjects_on_scene = scene.mobjects # TODO: the first argument seems wrong. Shouldn't it be scene instead? hash_play = get_hash_from_play_call( self, # type: ignore[arg-type] self.camera, animations, mobjects_on_scene, ) if self.file_writer.is_already_cached(hash_play): logger.info( f"Animation {self.num_plays} : Using cached data (hash : %(hash_play)s)", {"hash_play": hash_play}, ) self.skip_animations = True else: hash_play = f"uncached_{self.num_plays:05}" self.animations_hashes.append(hash_play) self.file_writer.add_partial_movie_file(hash_play) logger.debug( "List of the first few animation hashes of the scene: %(h)s", {"h": str(self.animations_hashes[:5])}, ) func(self, scene, *args, **kwargs) return wrapper ================================================ FILE: manim/utils/commands.py ================================================ from __future__ import annotations import os from collections.abc import Generator from pathlib import Path from subprocess import run from typing import TypedDict import av from manim.typing import StrOrBytesPath __all__ = [ "capture", "get_video_metadata", "get_dir_layout", ] def capture( command: str, cwd: StrOrBytesPath | None = None, command_input: str | None = None ) -> tuple[str, str, int]: p = run( command, cwd=cwd, input=command_input, capture_output=True, text=True, encoding="utf-8", ) out, err = p.stdout, p.stderr return out, err, p.returncode class VideoMetadata(TypedDict): width: int height: int nb_frames: str duration: str avg_frame_rate: str codec_name: str pix_fmt: str def get_video_metadata(path_to_video: str | os.PathLike) -> VideoMetadata: with av.open(str(path_to_video)) as container: stream = container.streams.video[0] ctxt = stream.codec_context rate = stream.average_rate if stream.duration is not None: duration = float(stream.duration * stream.time_base) num_frames = stream.frames else: num_frames = sum(1 for _ in container.decode(video=0)) duration = float(num_frames / stream.base_rate) return { "width": ctxt.width, "height": ctxt.height, "nb_frames": str(num_frames), "duration": f"{duration:.6f}", "avg_frame_rate": f"{rate.numerator}/{rate.denominator}", # Can be a Fraction "codec_name": stream.codec_context.name, "pix_fmt": stream.codec_context.pix_fmt, } def get_dir_layout(dirpath: Path) -> Generator[str, None, None]: """Get list of paths relative to dirpath of all files in dir and subdirs recursively.""" for p in dirpath.iterdir(): if p.is_dir(): yield from get_dir_layout(p) continue yield str(p.relative_to(dirpath)) ================================================ FILE: manim/utils/config_ops.py ================================================ """Utilities that might be useful for configuration dictionaries.""" from __future__ import annotations __all__ = [ "merge_dicts_recursively", "update_dict_recursively", "DictAsObject", ] import itertools as it from typing import Any, Generic, Protocol, cast import numpy.typing as npt from typing_extensions import TypeVar def merge_dicts_recursively(*dicts: dict[Any, Any]) -> dict[Any, Any]: """ Creates a dict whose keyset is the union of all the input dictionaries. The value for each key is based on the first dict in the list with that key. dicts later in the list have higher priority When values are dictionaries, it is applied recursively """ result: dict = {} all_items = it.chain(*(d.items() for d in dicts)) for key, value in all_items: if key in result and isinstance(result[key], dict) and isinstance(value, dict): result[key] = merge_dicts_recursively(result[key],
|
list with that key. dicts later in the list have higher priority When values are dictionaries, it is applied recursively """ result: dict = {} all_items = it.chain(*(d.items() for d in dicts)) for key, value in all_items: if key in result and isinstance(result[key], dict) and isinstance(value, dict): result[key] = merge_dicts_recursively(result[key], value) else: result[key] = value return result def update_dict_recursively( current_dict: dict[Any, Any], *others: dict[Any, Any] ) -> None: updated_dict = merge_dicts_recursively(current_dict, *others) current_dict.update(updated_dict) # Occasionally convenient in order to write dict.x instead of more laborious # (and less in keeping with all other attr accesses) dict["x"] class DictAsObject: def __init__(self, dictin: dict[str, Any]): self.__dict__ = dictin _Data_T = TypeVar("_Data_T", bound="npt.NDArray[Any]", default="npt.NDArray[Any]") class _HasData(Protocol): data: dict[str, npt.NDArray[Any]] class _Data(Generic[_Data_T]): """Descriptor that allows _Data variables to be grouped and accessed from self.data["attr"] via self.attr. self.data attributes must be arrays. """ def __set_name__(self, obj: _HasData, name: str) -> None: self.name: str = name def __get__(self, obj: _HasData, owner: Any) -> _Data_T: value = cast(_Data_T, obj.data[self.name]) return value def __set__(self, obj: _HasData, array: _Data_T) -> None: obj.data[self.name] = array _Uniforms_T = TypeVar("_Uniforms_T", bound="float | tuple[float, ...]", default=float) class _HasUniforms(Protocol): uniforms: dict[str, float | tuple[float, ...]] class _Uniforms(Generic[_Uniforms_T]): """Descriptor that allows _Uniforms variables to be grouped from self.uniforms["attr"] via self.attr. self.uniforms attributes must be floats or tuples of floats. """ def __set_name__(self, obj: _HasUniforms, name: str) -> None: self.name: str = name def __get__(self, obj: _HasUniforms, owner: Any) -> _Uniforms_T: val = cast(_Uniforms_T, obj.uniforms[self.name]) return val def __set__(self, obj: _HasUniforms, num: _Uniforms_T) -> None: obj.uniforms[self.name] = num ================================================ FILE: manim/utils/debug.py ================================================ """Debugging utilities.""" from __future__ import annotations __all__ = ["print_family", "index_labels"] from typing import Any from manim.mobject.mobject import Mobject from manim.mobject.text.numbers import Integer from manim.utils.color import ManimColor from ..mobject.types.vectorized_mobject import VGroup from .color import BLACK def print_family(mobject: Mobject, n_tabs: int = 0) -> None: """For debugging purposes""" print("\t" * n_tabs, mobject, id(mobject)) for submob in mobject.submobjects: print_family(submob, n_tabs + 1) def index_labels( mobject: Mobject, label_height: float = 0.15, background_stroke_width: float = 5, background_stroke_color: ManimColor = BLACK, **kwargs: Any, ) -> VGroup: r"""Returns a :class:`~.VGroup` of :class:`~.Integer` mobjects that shows the index of each submobject. Useful for working with parts of complicated mobjects. Parameters ---------- mobject The mobject that will have its submobjects labelled. label_height The height of the labels, by default 0.15. background_stroke_width The stroke width of the outline of the labels, by default 5. background_stroke_color The stroke color of the outline of labels. kwargs Additional parameters to be passed into the :class`~.Integer` mobjects used to construct the labels. Examples -------- .. manim:: IndexLabelsExample :save_last_frame: class IndexLabelsExample(Scene): def construct(self): text = MathTex( "\\frac{d}{dx}f(x)g(x)=", "f(x)\\frac{d}{dx}g(x)", "+", "g(x)\\frac{d}{dx}f(x)", ) #index the fist term in the MathTex mob indices = index_labels(text[0]) text[0][1].set_color(PURPLE_B) text[0][8:12].set_color(DARK_BLUE) self.add(text, indices) """ labels = VGroup() for n, submob in enumerate(mobject): label = Integer(n, **kwargs) label.set_stroke( background_stroke_color, background_stroke_width, background=True ) label.height = label_height label.move_to(submob) labels.add(label) return labels ================================================ FILE: manim/utils/deprecation.py ================================================ """Decorators for deprecating classes, functions and function parameters.""" from __future__ import annotations __all__ = ["deprecated", "deprecated_params"] import inspect import logging import re from collections.abc
|
VGroup() for n, submob in enumerate(mobject): label = Integer(n, **kwargs) label.set_stroke( background_stroke_color, background_stroke_width, background=True ) label.height = label_height label.move_to(submob) labels.add(label) return labels ================================================ FILE: manim/utils/deprecation.py ================================================ """Decorators for deprecating classes, functions and function parameters.""" from __future__ import annotations __all__ = ["deprecated", "deprecated_params"] import inspect import logging import re from collections.abc import Callable, Iterable from typing import Any, TypeVar, overload from decorator import decorate, decorator logger = logging.getLogger("manim") def _get_callable_info(callable_: Callable[..., Any], /) -> tuple[str, str]: """Returns type and name of a callable. Parameters ---------- callable The callable Returns ------- Tuple[str, str] The type and name of the callable. Type can can be one of "class", "method" (for functions defined in classes) or "function"). For methods, name is Class.method. """ what = type(callable_).__name__ name = callable_.__qualname__ if what == "function" and "." in name: what = "method" elif what != "function": what = "class" return (what, name) def _deprecation_text_component( since: str | None = None, until: str | None = None, message: str | None = None, ) -> str: """Generates a text component used in deprecation messages. Parameters ---------- since The version or date since deprecation until The version or date until removal of the deprecated callable message The reason for why the callable has been deprecated Returns ------- str The deprecation message text component. """ since = f"since {since} " if since else "" until = ( f"is expected to be removed after {until}" if until else "may be removed in a later version" ) msg = " " + message if message else "" return f"deprecated {since}and {until}.{msg}" # TODO: Use ParamSpec to type decorated functions when Python 3.9 is out of life T = TypeVar("T") @overload def deprecated( func: Callable[..., T], since: str | None = None, until: str | None = None, replacement: str | None = None, message: str | None = "", ) -> Callable[..., T]: ... @overload def deprecated( func: None = None, since: str | None = None, until: str | None = None, replacement: str | None = None, message: str | None = "", ) -> Callable[[Callable[..., T]], Callable[..., T]]: ... def deprecated( func: Callable[..., T] | None = None, since: str | None = None, until: str | None = None, replacement: str | None = None, message: str | None = "", ) -> Callable[..., T] | Callable[[Callable[..., T]], Callable[..., T]]: """Decorator to mark a callable as deprecated. The decorated callable will cause a warning when used. The docstring of the deprecated callable is adjusted to indicate that this callable is deprecated. Parameters ---------- func The function to be decorated. Should not be set by the user. since The version or date since deprecation. until The version or date until removal of the deprecated callable. replacement The identifier of the callable replacing the deprecated one. message The reason for why the callable has been deprecated. Returns ------- Callable The decorated callable. Examples -------- Basic usage:: from manim.utils.deprecation import deprecated @deprecated def foo(**kwargs): pass @deprecated class Bar: def __init__(self):
|
date until removal of the deprecated callable. replacement The identifier of the callable replacing the deprecated one. message The reason for why the callable has been deprecated. Returns ------- Callable The decorated callable. Examples -------- Basic usage:: from manim.utils.deprecation import deprecated @deprecated def foo(**kwargs): pass @deprecated class Bar: def __init__(self): pass @deprecated def baz(self): pass foo() # WARNING The function foo has been deprecated and may be removed in a later version. a = Bar() # WARNING The class Bar has been deprecated and may be removed in a later version. a.baz() # WARNING The method Bar.baz has been deprecated and may be removed in a later version. You can specify additional information for a more precise warning:: from manim.utils.deprecation import deprecated @deprecated( since="v0.2", until="v0.4", replacement="bar", message="It is cooler." ) def foo(): pass foo() # WARNING The function foo has been deprecated since v0.2 and is expected to be removed after v0.4. Use bar instead. It is cooler. You may also use dates instead of versions:: from manim.utils.deprecation import deprecated @deprecated(since="05/01/2021", until="06/01/2021") def foo(): pass foo() # WARNING The function foo has been deprecated since 05/01/2021 and is expected to be removed after 06/01/2021. """ # If used as factory: if func is None: return lambda func: deprecated(func, since, until, replacement, message) what, name = _get_callable_info(func) def warning_msg(for_docs: bool = False) -> str: """Generate the deprecation warning message. Parameters ---------- for_docs Whether or not to format the message for use in documentation. Returns ------- str The deprecation message. """ msg = message if replacement is not None: repl = replacement if for_docs: mapper = {"class": "class", "method": "meth", "function": "func"} repl = f":{mapper[what]}:`~.{replacement}`" msg = f"Use {repl} instead.{' ' + message if message else ''}" deprecated = _deprecation_text_component(since, until, msg) return f"The {what} {name} has been {deprecated}" def deprecate_docs(func: Callable) -> None: """Adjust docstring to indicate the deprecation. Parameters ---------- func The callable whose docstring to adjust. """ warning = warning_msg(True) doc_string = func.__doc__ or "" func.__doc__ = f"{doc_string}\n\n.. attention:: Deprecated\n {warning}" def deprecate(func: Callable[..., T], *args: Any, **kwargs: Any) -> T: """The actual decorator used to extend the callables behavior. Logs a warning message. Parameters ---------- func The callable to decorate. args The arguments passed to the given callable. kwargs The keyword arguments passed to the given callable. Returns ------- Any The return value of the given callable when being passed the given arguments. """ logger.warning(warning_msg()) return func(*args, **kwargs) if type(func).__name__ != "function": deprecate_docs(func) func.__init__ = decorate(func.__init__, deprecate) return func func = decorate(func, deprecate) deprecate_docs(func) return func def deprecated_params( params: str | Iterable[str] | None = None, since: str | None = None, until: str | None = None, message: str = "", redirections: None | (Iterable[tuple[str, str] | Callable[..., dict[str, Any]]]) = None, ) -> Callable[..., T]: """Decorator to mark parameters of a callable as deprecated. It can also be used to automatically redirect deprecated parameter values to their replacements. Parameters ---------- params The parameters to be deprecated. Can consist of: * An iterable of strings, with each
|
Callable[..., dict[str, Any]]]) = None, ) -> Callable[..., T]: """Decorator to mark parameters of a callable as deprecated. It can also be used to automatically redirect deprecated parameter values to their replacements. Parameters ---------- params The parameters to be deprecated. Can consist of: * An iterable of strings, with each element representing a parameter to deprecate * A single string, with parameter names separated by commas or spaces. since The version or date since deprecation. until The version or date until removal of the deprecated callable. message The reason for why the callable has been deprecated. redirections A list of parameter redirections. Each redirection can be one of the following: * A tuple of two strings. The first string defines the name of the deprecated parameter; the second string defines the name of the parameter to redirect to, when attempting to use the first string. * A function performing the mapping operation. The parameter names of the function determine which parameters are used as input. The function must return a dictionary which contains the redirected arguments. Redirected parameters are also implicitly deprecated. Returns ------- Callable The decorated callable. Raises ------ ValueError If no parameters are defined (neither explicitly nor implicitly). ValueError If defined parameters are invalid python identifiers. Examples -------- Basic usage:: from manim.utils.deprecation import deprecated_params @deprecated_params(params="a, b, c") def foo(**kwargs): pass foo(x=2, y=3, z=4) # No warning foo(a=2, b=3, z=4) # WARNING The parameters a and b of method foo have been deprecated and may be removed in a later version. You can also specify additional information for a more precise warning:: from manim.utils.deprecation import deprecated_params @deprecated_params( params="a, b, c", since="v0.2", until="v0.4", message="The letters x, y, z are cooler.", ) def foo(**kwargs): pass foo(a=2) # WARNING The parameter a of method foo has been deprecated since v0.2 and is expected to be removed after v0.4. The letters x, y, z are cooler. Basic parameter redirection:: from manim.utils.deprecation import deprecated_params @deprecated_params( redirections=[ # Two ways to redirect one parameter to another: ("old_param", "new_param"), lambda old_param2: {"new_param22": old_param2}, ] ) def foo(**kwargs): return kwargs foo(x=1, old_param=2) # WARNING The parameter old_param of method foo has been deprecated and may be removed in a later version. # returns {"x": 1, "new_param": 2} Redirecting using a calculated value:: from manim.utils.deprecation import deprecated_params @deprecated_params( redirections=[lambda runtime_in_ms: {"run_time": runtime_in_ms / 1000}] ) def foo(**kwargs): return kwargs foo(runtime_in_ms=500) # WARNING The parameter runtime_in_ms of method foo has been deprecated and may be removed in a later version. # returns {"run_time": 0.5} Redirecting multiple parameter values to one:: from manim.utils.deprecation import deprecated_params @deprecated_params( redirections=[lambda buff_x=1, buff_y=1: {"buff": (buff_x, buff_y)}] ) def foo(**kwargs): return kwargs foo(buff_x=2) # WARNING The parameter buff_x of method foo has been deprecated and may be removed in a later version. # returns {"buff": (2, 1)} Redirect one parameter to multiple:: from manim.utils.deprecation import deprecated_params @deprecated_params( redirections=[ lambda buff=1: {"buff_x": buff[0], "buff_y": buff[1]} if isinstance(buff, tuple) else {"buff_x": buff, "buff_y": buff} ] ) def foo(**kwargs): return kwargs foo(buff=0) # WARNING The parameter buff of
|
may be removed in a later version. # returns {"buff": (2, 1)} Redirect one parameter to multiple:: from manim.utils.deprecation import deprecated_params @deprecated_params( redirections=[ lambda buff=1: {"buff_x": buff[0], "buff_y": buff[1]} if isinstance(buff, tuple) else {"buff_x": buff, "buff_y": buff} ] ) def foo(**kwargs): return kwargs foo(buff=0) # WARNING The parameter buff of method foo has been deprecated and may be removed in a later version. # returns {"buff_x": 0, buff_y: 0} foo(buff=(1, 2)) # WARNING The parameter buff of method foo has been deprecated and may be removed in a later version. # returns {"buff_x": 1, buff_y: 2} """ # Check if decorator is used without parenthesis if callable(params): raise ValueError("deprecate_parameters requires arguments to be specified.") if params is None: params = [] # Construct params list params = re.split(r"[,\s]+", params) if isinstance(params, str) else list(params) # Add params which are only implicitly given via redirections if redirections is None: redirections = [] for redirector in redirections: if isinstance(redirector, tuple): params.append(redirector[0]) else: params.extend(list(inspect.signature(redirector).parameters)) # Keep ordering of params so that warning message is consistently the same # This will also help pass unit testing params = list(dict.fromkeys(params)) # Make sure params only contains valid identifiers identifier = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE) if not all(re.match(identifier, param) for param in params): raise ValueError("Given parameter values are invalid.") redirections = list(redirections) def warning_msg(func: Callable[..., T], used: list[str]) -> str: """Generate the deprecation warning message. Parameters ---------- func The callable with deprecated parameters. used The list of deprecated parameters used in a call. Returns ------- str The deprecation message. """ what, name = _get_callable_info(func) plural = len(used) > 1 parameter_s = "s" if plural else "" used_ = ", ".join(used[:-1]) + " and " + used[-1] if plural else used[0] has_have_been = "have been" if plural else "has been" deprecated = _deprecation_text_component(since, until, message) return f"The parameter{parameter_s} {used_} of {what} {name} {has_have_been} {deprecated}" def redirect_params(kwargs: dict[str, Any], used: list[str]) -> None: """Adjust the keyword arguments as defined by the redirections. Parameters ---------- kwargs The keyword argument dictionary to be updated. used The list of deprecated parameters used in a call. """ for redirector in redirections: if isinstance(redirector, tuple): old_param, new_param = redirector if old_param in used: kwargs[new_param] = kwargs.pop(old_param) else: redirector_params = list(inspect.signature(redirector).parameters) redirector_args = {} for redirector_param in redirector_params: if redirector_param in used: redirector_args[redirector_param] = kwargs.pop(redirector_param) if len(redirector_args) > 0: kwargs.update(redirector(**redirector_args)) def deprecate_params(func: Callable[..., T], *args: Any, **kwargs: Any) -> T: """The actual decorator function used to extend the callables behavior. Logs a warning message when a deprecated parameter is used and redirects it if specified. Parameters ---------- func The callable to decorate. args The arguments passed to the given callable. kwargs The keyword arguments passed to the given callable. Returns ------- Any The return value of the given callable when being passed the given arguments. """ used = [] for param in params: if param in kwargs: used.append(param) if len(used) > 0: logger.warning(warning_msg(func, used)) redirect_params(kwargs, used) return func(*args, **kwargs) return decorator(deprecate_params) # type: ignore[return-value] ================================================ FILE: manim/utils/exceptions.py ================================================ from __future__ import annotations __all__ = [ "EndSceneEarlyException",
|
the given callable when being passed the given arguments. """ used = [] for param in params: if param in kwargs: used.append(param) if len(used) > 0: logger.warning(warning_msg(func, used)) redirect_params(kwargs, used) return func(*args, **kwargs) return decorator(deprecate_params) # type: ignore[return-value] ================================================ FILE: manim/utils/exceptions.py ================================================ from __future__ import annotations __all__ = [ "EndSceneEarlyException", "RerunSceneException", "MultiAnimationOverrideException", ] class EndSceneEarlyException(Exception): pass class RerunSceneException(Exception): pass class MultiAnimationOverrideException(Exception): pass ================================================ FILE: manim/utils/family.py ================================================ from __future__ import annotations import itertools as it from collections.abc import Iterable from ..mobject.mobject import Mobject from ..utils.iterables import remove_list_redundancies __all__ = ["extract_mobject_family_members"] def extract_mobject_family_members( mobjects: Iterable[Mobject], use_z_index: bool = False, only_those_with_points: bool = False, ) -> list[Mobject]: """Returns a list of the types of mobjects and their family members present. A "family" in this context refers to a mobject, its submobjects, and their submobjects, recursively. Parameters ---------- mobjects The Mobjects currently in the Scene only_those_with_points Whether or not to only do this for those mobjects that have points. By default False Returns ------- list list of the mobjects and family members. """ if only_those_with_points: method = Mobject.family_members_with_points else: method = Mobject.get_family extracted_mobjects = remove_list_redundancies( list(it.chain(*(method(m) for m in mobjects))), ) if use_z_index: return sorted(extracted_mobjects, key=lambda m: m.z_index) return extracted_mobjects ================================================ FILE: manim/utils/family_ops.py ================================================ from __future__ import annotations import itertools as it from manim.mobject.mobject import Mobject __all__ = [ "extract_mobject_family_members", "restructure_list_to_exclude_certain_family_members", ] def extract_mobject_family_members( mobject_list: list[Mobject], only_those_with_points: bool = False ) -> list[Mobject]: result = list(it.chain(*(mob.get_family() for mob in mobject_list))) if only_those_with_points: result = [mob for mob in result if mob.has_points()] return result def restructure_list_to_exclude_certain_family_members( mobject_list: list[Mobject], to_remove: list[Mobject] ) -> list[Mobject]: """ Removes anything in to_remove from mobject_list, but in the event that one of the items to be removed is a member of the family of an item in mobject_list, the other family members are added back into the list. This is useful in cases where a scene contains a group, e.g. Group(m1, m2, m3), but one of its submobjects is removed, e.g. scene.remove(m1), it's useful for the list of mobject_list to be edited to contain other submobjects, but not m1. """ new_list: list[Mobject] = [] to_remove = extract_mobject_family_members(to_remove) def add_safe_mobjects_from_list( list_to_examine: list[Mobject], set_to_remove: set[Mobject] ) -> None: for mob in list_to_examine: if mob in set_to_remove: continue intersect = set_to_remove.intersection(mob.get_family()) if intersect: add_safe_mobjects_from_list(mob.submobjects, intersect) else: new_list.append(mob) add_safe_mobjects_from_list(mobject_list, set(to_remove)) return new_list ================================================ FILE: manim/utils/file_ops.py ================================================ """Utility functions for interacting with the file system.""" from __future__ import annotations __all__ = [ "add_extension_if_not_present", "guarantee_existence", "guarantee_empty_existence", "seek_full_path_from_defaults", "modify_atime", "open_file", "is_mp4_format", "is_gif_format", "is_png_format", "is_webm_format", "is_mov_format", "write_to_movie", "ensure_executable", ] import os import platform import shutil import subprocess as sp import time from pathlib import Path from shutil import copyfile from typing import TYPE_CHECKING if TYPE_CHECKING: from manim.typing import StrPath from ..scene.scene_file_writer import SceneFileWriter from manim import __version__, config, logger from .. import console def is_mp4_format() -> bool: """ Determines if output format is .mp4 Returns ------- class:`bool` ``True`` if format is set as mp4 """ val: bool = config["format"] == "mp4" return val def is_gif_format() -> bool: """ Determines if output format is .gif Returns ------- class:`bool` ``True``
|
logger from .. import console def is_mp4_format() -> bool: """ Determines if output format is .mp4 Returns ------- class:`bool` ``True`` if format is set as mp4 """ val: bool = config["format"] == "mp4" return val def is_gif_format() -> bool: """ Determines if output format is .gif Returns ------- class:`bool` ``True`` if format is set as gif """ val: bool = config["format"] == "gif" return val def is_webm_format() -> bool: """ Determines if output format is .webm Returns ------- class:`bool` ``True`` if format is set as webm """ val: bool = config["format"] == "webm" return val def is_mov_format() -> bool: """ Determines if output format is .mov Returns ------- class:`bool` ``True`` if format is set as mov """ val: bool = config["format"] == "mov" return val def is_png_format() -> bool: """ Determines if output format is .png Returns ------- class:`bool` ``True`` if format is set as png """ val: bool = config["format"] == "png" return val def write_to_movie() -> bool: """ Determines from config if the output is a video format such as mp4 or gif, if the --format is set as 'png' then it will take precedence event if the write_to_movie flag is set Returns ------- class:`bool` ``True`` if the output should be written in a movie format """ if is_png_format(): return False return ( config["write_to_movie"] or is_mp4_format() or is_gif_format() or is_webm_format() or is_mov_format() ) def ensure_executable(path_to_exe: Path) -> bool: if path_to_exe.parent == Path("."): executable: StrPath | None = shutil.which(path_to_exe.stem) if executable is None: return False else: executable = path_to_exe return os.access(executable, os.X_OK) def add_extension_if_not_present(file_name: Path, extension: str) -> Path: if file_name.suffix != extension: return file_name.with_suffix(file_name.suffix + extension) else: return file_name def add_version_before_extension(file_name: Path) -> Path: return file_name.with_name( f"{file_name.stem}_ManimCE_v{__version__}{file_name.suffix}" ) def guarantee_existence(path: Path) -> Path: if not path.exists(): path.mkdir(parents=True) return path.resolve(strict=True) def guarantee_empty_existence(path: Path) -> Path: if path.exists(): shutil.rmtree(str(path)) path.mkdir(parents=True) return path.resolve(strict=True) def seek_full_path_from_defaults( file_name: StrPath, default_dir: Path, extensions: list[str] ) -> Path: possible_paths = [Path(file_name).expanduser()] possible_paths += [ Path(default_dir) / f"{file_name}{extension}" for extension in ["", *extensions] ] for path in possible_paths: if path.exists(): return path error = ( f"From: {Path.cwd()}, could not find {file_name} at either " f"of these locations: {list(map(str, possible_paths))}" ) raise OSError(error) def modify_atime(file_path: str) -> None: """Will manually change the accessed time (called `atime`) of the file, as on a lot of OS the accessed time refresh is disabled by default. Parameters ---------- file_path The path of the file. """ os.utime(file_path, times=(time.time(), Path(file_path).stat().st_mtime)) def open_file(file_path: Path, in_browser: bool = False) -> None: current_os = platform.system() if current_os == "Windows": # The method os.startfile is only available in Windows, # ignoring type error caused by this. os.startfile(file_path if not in_browser else file_path.parent) # type: ignore[attr-defined] else: if current_os == "Linux": commands = ["xdg-open"] file_path = file_path if not in_browser else file_path.parent elif current_os.startswith("CYGWIN"): commands = ["cygstart"] file_path = file_path if not in_browser else file_path.parent elif current_os == "Darwin": commands = ["open"] if not in_browser else ["open", "-R"] else: raise OSError("Unable to identify your operating system...") # check after so that file path is set correctly if
|
if not in_browser else file_path.parent elif current_os.startswith("CYGWIN"): commands = ["cygstart"] file_path = file_path if not in_browser else file_path.parent elif current_os == "Darwin": commands = ["open"] if not in_browser else ["open", "-R"] else: raise OSError("Unable to identify your operating system...") # check after so that file path is set correctly if config.preview_command: commands = [config.preview_command] commands.append(str(file_path)) sp.run(commands) def open_media_file(file_writer: SceneFileWriter) -> None: file_paths = [] if config["save_last_frame"]: file_paths.append(file_writer.image_file_path) if write_to_movie() and not is_gif_format(): file_paths.append(file_writer.movie_file_path) if write_to_movie() and is_gif_format(): file_paths.append(file_writer.gif_file_path) for file_path in file_paths: if config["show_in_file_browser"]: open_file(file_path, True) if config["preview"]: open_file(file_path, False) logger.info(f"Previewed File at: '{file_path}'") def get_template_names() -> list[str]: """Returns template names from the templates directory. Returns ------- :class:`list` """ template_path = Path.resolve(Path(__file__).parent.parent / "templates") return [template_name.stem for template_name in template_path.glob("*.mtp")] def get_template_path() -> Path: """Returns the Path of templates directory. Returns ------- :class:`Path` """ return Path.resolve(Path(__file__).parent.parent / "templates") def add_import_statement(file: Path) -> None: """Prepends an import statement in a file Parameters ---------- file """ with file.open("r+") as f: import_line = "from manim import *" content = f.read() f.seek(0) f.write(import_line + "\n" + content) def copy_template_files( project_dir: Path = Path("."), template_name: str = "Default" ) -> None: """Copies template files from templates dir to project_dir. Parameters ---------- project_dir Path to project directory. template_name Name of template. """ template_cfg_path = Path.resolve( Path(__file__).parent.parent / "templates/template.cfg", ) template_scene_path = Path.resolve( Path(__file__).parent.parent / f"templates/{template_name}.mtp", ) if not template_cfg_path.exists(): raise FileNotFoundError(f"{template_cfg_path} : file does not exist") if not template_scene_path.exists(): raise FileNotFoundError(f"{template_scene_path} : file does not exist") copyfile(template_cfg_path, Path.resolve(project_dir / "manim.cfg")) console.print("\n\t[green]copied[/green] [blue]manim.cfg[/blue]\n") copyfile(template_scene_path, Path.resolve(project_dir / "main.py")) console.print("\n\t[green]copied[/green] [blue]main.py[/blue]\n") add_import_statement(Path.resolve(project_dir / "main.py")) ================================================ FILE: manim/utils/hashing.py ================================================ """Utilities for scene caching.""" from __future__ import annotations import copy import inspect import json import zlib from collections.abc import Callable, Hashable, Iterable from time import perf_counter from types import FunctionType, MappingProxyType, MethodType, ModuleType from typing import TYPE_CHECKING, Any import numpy as np from manim._config import config, logger if TYPE_CHECKING: from manim.animation.animation import Animation from manim.camera.camera import Camera from manim.mobject.mobject import Mobject from manim.renderer.opengl_renderer import OpenGLCamera from manim.scene.scene import Scene __all__ = ["KEYS_TO_FILTER_OUT", "get_hash_from_play_call", "get_json"] # Sometimes there are elements that are not suitable for hashing (too long or # run-dependent). This is used to filter them out. KEYS_TO_FILTER_OUT = { "original_id", "background", "pixel_array", "pixel_array_to_cairo_context", } class _Memoizer: """Implements the memoization logic to optimize the hashing procedure and prevent the circular references within iterable processed. Keeps a record of all the processed objects, and handle the logic to return a place holder instead of the original object if the object has already been processed by the hashing logic (i.e, recursively checked, converted to JSON, etc..). This class uses two signatures functions to keep a track of processed objects : hash or id. Whenever possible, hash is used to ensure a broader object content-equality detection. """ _already_processed = set() # Can be changed to whatever string to help debugging the JSon generation. ALREADY_PROCESSED_PLACEHOLDER = "AP" THRESHOLD_WARNING = 170_000 @classmethod def reset_already_processed(cls): cls._already_processed.clear() @classmethod def check_already_processed_decorator(cls: _Memoizer, is_method: bool = False): """Decorator to handle the arguments that goes through the decorated function. Returns _ALREADY_PROCESSED_PLACEHOLDER
|
content-equality detection. """ _already_processed = set() # Can be changed to whatever string to help debugging the JSon generation. ALREADY_PROCESSED_PLACEHOLDER = "AP" THRESHOLD_WARNING = 170_000 @classmethod def reset_already_processed(cls): cls._already_processed.clear() @classmethod def check_already_processed_decorator(cls: _Memoizer, is_method: bool = False): """Decorator to handle the arguments that goes through the decorated function. Returns _ALREADY_PROCESSED_PLACEHOLDER if the obj has been processed, or lets the decorated function call go ahead. Parameters ---------- is_method Whether the function passed is a method, by default False. """ def layer(func): # NOTE : There is probably a better way to separate both case when func is # a method or a function. if is_method: return lambda self, obj: cls._handle_already_processed( obj, default_function=lambda obj: func(self, obj), ) return lambda obj: cls._handle_already_processed(obj, default_function=func) return layer @classmethod def check_already_processed(cls, obj: Any) -> Any: """Checks if obj has been already processed. Returns itself if it has not been, or the value of _ALREADY_PROCESSED_PLACEHOLDER if it has. Marks the object as processed in the second case. Parameters ---------- obj The object to check. Returns ------- Any Either the object itself or the placeholder. """ # When the object is not memoized, we return the object itself. return cls._handle_already_processed(obj, lambda x: x) @classmethod def mark_as_processed(cls, obj: Any) -> None: """Marks an object as processed. Parameters ---------- obj The object to mark as processed. """ cls._handle_already_processed(obj, lambda x: x) return cls._return(obj, id, lambda x: x, memoizing=False) @classmethod def _handle_already_processed( cls, obj, default_function: Callable[[Any], Any], ): if isinstance( obj, ( int, float, str, complex, ), ) and obj not in [None, cls.ALREADY_PROCESSED_PLACEHOLDER]: # It makes no sense (and it'd slower) to memoize objects of these primitive # types. Hence, we simply return the object. return obj if isinstance(obj, Hashable): try: return cls._return(obj, hash, default_function) except TypeError: # In case of an error with the hash (eg an object is marked as hashable # but contains a non hashable within it) # Fallback to use the built-in function id instead. pass return cls._return(obj, id, default_function) @classmethod def _return( cls, obj: Any, obj_to_membership_sign: Callable[[Any], int], default_func, memoizing=True, ) -> str | Any: obj_membership_sign = obj_to_membership_sign(obj) if obj_membership_sign in cls._already_processed: return cls.ALREADY_PROCESSED_PLACEHOLDER if memoizing: if ( not config.disable_caching_warning and len(cls._already_processed) == cls.THRESHOLD_WARNING ): logger.warning( "It looks like the scene contains a lot of sub-mobjects. Caching " "is sometimes not suited to handle such large scenes, you might " "consider disabling caching with --disable_caching to potentially " "speed up the rendering process.", ) logger.warning( "You can disable this warning by setting disable_caching_warning " "to True in your config file.", ) cls._already_processed.add(obj_membership_sign) return default_func(obj) class _CustomEncoder(json.JSONEncoder): def default(self, obj: Any): """ This method is used to serialize objects to JSON format. If obj is a function, then it will return a dict with two keys : 'code', for the code source, and 'nonlocals' for all nonlocalsvalues. (including nonlocals functions, that will be serialized as this is recursive.) if obj is a np.darray, it converts it into a list. if obj is an object with __dict__ attribute, it returns its __dict__. Else, will let the
|
keys : 'code', for the code source, and 'nonlocals' for all nonlocalsvalues. (including nonlocals functions, that will be serialized as this is recursive.) if obj is a np.darray, it converts it into a list. if obj is an object with __dict__ attribute, it returns its __dict__. Else, will let the JSONEncoder do the stuff, and throw an error if the type is not suitable for JSONEncoder. Parameters ---------- obj Arbitrary object to convert Returns ------- Any Python object that JSON encoder will recognize """ if not (isinstance(obj, ModuleType)) and isinstance( obj, (MethodType, FunctionType), ): cvars = inspect.getclosurevars(obj) cvardict = {**copy.copy(cvars.globals), **copy.copy(cvars.nonlocals)} for i in list(cvardict): # NOTE : All module types objects are removed, because otherwise it # throws ValueError: Circular reference detected if not. TODO if isinstance(cvardict[i], ModuleType): del cvardict[i] try: code = inspect.getsource(obj) except (OSError, TypeError): # This happens when rendering videos included in the documentation # within doctests and should be replaced by a solution avoiding # hash collision (due to the same, empty, code strings) at some point. # See https://github.com/ManimCommunity/manim/pull/402. code = "" return self._cleaned_iterable({"code": code, "nonlocals": cvardict}) elif isinstance(obj, np.ndarray): if obj.size > 1000: obj = np.resize(obj, (100, 100)) return f"TRUNCATED ARRAY: {repr(obj)}" # We return the repr and not a list to avoid the JsonEncoder to iterate over it. return repr(obj) elif hasattr(obj, "__dict__"): temp = obj.__dict__ # MappingProxy is scene-caching nightmare. It contains all of the object methods and attributes. We skip it as the mechanism will at some point process the object, but instantiated. # Indeed, there is certainly no case where scene-caching will receive only a non instancied object, as this is never used in the library or encouraged to be used user-side. if isinstance(temp, MappingProxyType): return "MappingProxy" return self._cleaned_iterable(temp) elif isinstance(obj, np.uint8): return int(obj) # Serialize it with only the type of the object. You can change this to whatever string when debugging the serialization process. return str(type(obj)) def _cleaned_iterable(self, iterable: Iterable[Any]): """Check for circular reference at each iterable that will go through the JSONEncoder, as well as key of the wrong format. If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here. If a circular reference is found within the iterable, it will be replaced by the string "already processed". Parameters ---------- iterable The iterable to check. """ def _key_to_hash(key): return zlib.crc32(json.dumps(key, cls=_CustomEncoder).encode()) def _iter_check_list(lst): processed_list = [None] * len(lst) for i, el in enumerate(lst): el = _Memoizer.check_already_processed(el) if isinstance(el, (list, tuple)): new_value = _iter_check_list(el) elif isinstance(el, dict): new_value = _iter_check_dict(el) else: new_value = el processed_list[i] = new_value return processed_list def _iter_check_dict(dct): processed_dict = {} for k, v in dct.items(): v = _Memoizer.check_already_processed(v) if k in KEYS_TO_FILTER_OUT: continue # We check if the k is of the right format (supporter by Json) if not isinstance(k, (str, int, float, bool)) and k is not None: k_new = _key_to_hash(k) else: k_new = k if isinstance(v, dict): new_value = _iter_check_dict(v) elif isinstance(v, (list,
|
v = _Memoizer.check_already_processed(v) if k in KEYS_TO_FILTER_OUT: continue # We check if the k is of the right format (supporter by Json) if not isinstance(k, (str, int, float, bool)) and k is not None: k_new = _key_to_hash(k) else: k_new = k if isinstance(v, dict): new_value = _iter_check_dict(v) elif isinstance(v, (list, tuple)): new_value = _iter_check_list(v) else: new_value = v processed_dict[k_new] = new_value return processed_dict if isinstance(iterable, (list, tuple)): return _iter_check_list(iterable) elif isinstance(iterable, dict): return _iter_check_dict(iterable) def encode(self, obj: Any): """Overriding of :meth:`JSONEncoder.encode`, to make our own process. Parameters ---------- obj The object to encode in JSON. Returns ------- :class:`str` The object encoder with the standard json process. """ _Memoizer.mark_as_processed(obj) if isinstance(obj, (dict, list, tuple)): return super().encode(self._cleaned_iterable(obj)) return super().encode(obj) def get_json(obj: dict): """Recursively serialize `object` to JSON using the :class:`CustomEncoder` class. Parameters ---------- obj The dict to flatten Returns ------- :class:`str` The flattened object """ return json.dumps(obj, cls=_CustomEncoder) def get_hash_from_play_call( scene_object: Scene, camera_object: Camera | OpenGLCamera, animations_list: Iterable[Animation], current_mobjects_list: Iterable[Mobject], ) -> str: """Take the list of animations and a list of mobjects and output their hashes. This is meant to be used for `scene.play` function. Parameters ----------- scene_object The scene object. camera_object The camera object used in the scene. animations_list The list of animations. current_mobjects_list The list of mobjects. Returns ------- :class:`str` A string concatenation of the respective hashes of `camera_object`, `animations_list` and `current_mobjects_list`, separated by `_`. """ logger.debug("Hashing ...") t_start = perf_counter() _Memoizer.mark_as_processed(scene_object) camera_json = get_json(camera_object) animations_list_json = [get_json(x) for x in sorted(animations_list, key=str)] current_mobjects_list_json = [get_json(x) for x in current_mobjects_list] hash_camera, hash_animations, hash_current_mobjects = ( zlib.crc32(repr(json_val).encode()) for json_val in [camera_json, animations_list_json, current_mobjects_list_json] ) hash_complete = f"{hash_camera}_{hash_animations}_{hash_current_mobjects}" t_end = perf_counter() logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]}) # End of the hashing for the animation, reset all the memoize. _Memoizer.reset_already_processed() logger.debug("Hash generated : %(h)s", {"h": hash_complete}) return hash_complete ================================================ FILE: manim/utils/images.py ================================================ """Image manipulation utilities.""" from __future__ import annotations __all__ = [ "get_full_raster_image_path", "drag_pixels", "invert_image", "change_to_rgba_array", ] from pathlib import Path, PurePath from typing import TYPE_CHECKING import numpy as np from PIL import Image from manim.typing import RGBAPixelArray, RGBPixelArray from .. import config from ..utils.file_ops import seek_full_path_from_defaults if TYPE_CHECKING: pass def get_full_raster_image_path(image_file_name: str | PurePath) -> Path: return seek_full_path_from_defaults( image_file_name, default_dir=config.get_dir("assets_dir"), extensions=[".jpg", ".jpeg", ".png", ".gif", ".ico"], ) def get_full_vector_image_path(image_file_name: str | PurePath) -> Path: return seek_full_path_from_defaults( image_file_name, default_dir=config.get_dir("assets_dir"), extensions=[".svg"], ) def drag_pixels(frames: list[np.array]) -> list[np.array]: curr = frames[0] new_frames = [] for frame in frames: curr += (curr == 0) * np.array(frame) new_frames.append(np.array(curr)) return new_frames def invert_image(image: np.array) -> Image: arr = np.array(image) arr = (255 * np.ones(arr.shape)).astype(arr.dtype) - arr return Image.fromarray(arr) def change_to_rgba_array(image: RGBPixelArray, dtype: str = "uint8") -> RGBAPixelArray: """Converts an RGB array into RGBA with the alpha value opacity maxed.""" pa = image if len(pa.shape) == 2: pa = pa.reshape(list(pa.shape) + [1]) if pa.shape[2] == 1: pa = pa.repeat(3, axis=2) if pa.shape[2] == 3: alphas = 255 * np.ones( list(pa.shape[:2]) + [1], dtype=dtype, ) pa = np.append(pa, alphas, axis=2) return pa ================================================ FILE: manim/utils/ipython_magic.py ================================================ """Utilities for using Manim with IPython (in particular: Jupyter notebooks)"""
|
== 2: pa = pa.reshape(list(pa.shape) + [1]) if pa.shape[2] == 1: pa = pa.repeat(3, axis=2) if pa.shape[2] == 3: alphas = 255 * np.ones( list(pa.shape[:2]) + [1], dtype=dtype, ) pa = np.append(pa, alphas, axis=2) return pa ================================================ FILE: manim/utils/ipython_magic.py ================================================ """Utilities for using Manim with IPython (in particular: Jupyter notebooks)""" from __future__ import annotations import mimetypes import shutil from datetime import datetime from pathlib import Path from typing import Any from manim import config, logger, tempconfig from manim.__main__ import main from manim.renderer.shader import shader_program_cache from ..constants import RendererType __all__ = ["ManimMagic"] try: from IPython import get_ipython from IPython.core.interactiveshell import InteractiveShell from IPython.core.magic import ( Magics, line_cell_magic, magics_class, needs_local_scope, ) from IPython.display import Image, Video, display except ImportError: pass else: @magics_class class ManimMagic(Magics): def __init__(self, shell: InteractiveShell) -> None: super().__init__(shell) self.rendered_files: dict[Path, Path] = {} @needs_local_scope @line_cell_magic def manim( self, line: str, cell: str | None = None, local_ns: dict[str, Any] | None = None, ) -> None: r"""Render Manim scenes contained in IPython cells. Works as a line or cell magic. .. hint:: This line and cell magic works best when used in a JupyterLab environment: while all of the functionality is available for classic Jupyter notebooks as well, it is possible that videos sometimes don't update on repeated execution of the same cell if the scene name stays the same. This problem does not occur when using JupyterLab. Please refer to `<https://jupyter.org/>`_ for more information about JupyterLab and Jupyter notebooks. Usage in line mode:: %manim [CLI options] MyAwesomeScene Usage in cell mode:: %%manim [CLI options] MyAwesomeScene class MyAweseomeScene(Scene): def construct(self): ... Run ``%manim --help`` and ``%manim render --help`` for possible command line interface options. .. note:: The maximal width of the rendered videos that are displayed in the notebook can be configured via the ``media_width`` configuration option. The default is set to ``25vw``, which is 25% of your current viewport width. To allow the output to become as large as possible, set ``config.media_width = "100%"``. The ``media_embed`` option will embed the image/video output in the notebook. This is generally undesirable as it makes the notebooks very large, but is required on some platforms (notably Google's CoLab, where it is automatically enabled unless suppressed by ``config.embed = False``) and needed in cases when the notebook (or converted HTML file) will be moved relative to the video locations. Use-cases include building documentation with Sphinx and JupyterBook. See also the :mod:`manim directive for Sphinx <manim.utils.docbuild.manim_directive>`. Examples -------- First make sure to put ``import manim``, or even ``from manim import *`` in a cell and evaluate it. Then, a typical Jupyter notebook cell for Manim could look as follows:: %%manim -v WARNING --disable_caching -qm BannerExample config.media_width = "75%" config.media_embed = True class BannerExample(Scene): def construct(self): self.camera.background_color = "#ece6e2" banner_large = ManimBanner(dark_theme=False).scale(0.7) self.play(banner_large.create()) self.play(banner_large.expand()) Evaluating this cell will render and display the ``BannerExample`` scene defined in the body of the cell. .. note:: In case you want to hide the red box containing the output progress bar, the ``progress_bar`` config option should be set
|
def construct(self): self.camera.background_color = "#ece6e2" banner_large = ManimBanner(dark_theme=False).scale(0.7) self.play(banner_large.create()) self.play(banner_large.expand()) Evaluating this cell will render and display the ``BannerExample`` scene defined in the body of the cell. .. note:: In case you want to hide the red box containing the output progress bar, the ``progress_bar`` config option should be set to ``None``. This can also be done by passing ``--progress_bar None`` as a CLI flag. """ if cell: exec(cell, local_ns) args = line.split() if not len(args) or "-h" in args or "--help" in args or "--version" in args: main(args, standalone_mode=False, prog_name="manim") return modified_args = self.add_additional_args(args) args = main(modified_args, standalone_mode=False, prog_name="manim") assert isinstance(local_ns, dict) with tempconfig(local_ns.get("config", {})): config.digest_args(args) renderer = None if config.renderer == RendererType.OPENGL: from manim.renderer.opengl_renderer import OpenGLRenderer renderer = OpenGLRenderer() try: SceneClass = local_ns[config["scene_names"][0]] scene = SceneClass(renderer=renderer) scene.render() finally: # Shader cache becomes invalid as the context is destroyed shader_program_cache.clear() # Close OpenGL window here instead of waiting for the main thread to # finish causing the window to stay open and freeze if renderer is not None and renderer.window is not None: renderer.window.close() if config["output_file"] is None: logger.info("No output file produced") return local_path = Path(config["output_file"]).relative_to(Path.cwd()) tmpfile = ( Path(config["media_dir"]) / "jupyter" / f"{_generate_file_name()}{local_path.suffix}" ) if local_path in self.rendered_files: self.rendered_files[local_path].unlink() self.rendered_files[local_path] = tmpfile tmpfile.parent.mkdir(parents=True, exist_ok=True) shutil.copy(local_path, tmpfile) file_type = mimetypes.guess_type(config["output_file"])[0] assert isinstance(file_type, str) embed = config["media_embed"] if not embed: # videos need to be embedded when running in google colab. # do this automatically in case config.media_embed has not been # set explicitly. embed = "google.colab" in str(get_ipython()) if file_type.startswith("image"): result = Image(filename=config["output_file"]) else: result = Video( tmpfile, html_attributes=f'controls autoplay loop style="max-width: {config["media_width"]};"', embed=embed, ) display(result) def add_additional_args(self, args: list[str]) -> list[str]: additional_args = ["--jupyter"] # Use webm to support transparency if "-t" in args and "--format" not in args: additional_args += ["--format", "webm"] return additional_args + args[:-1] + [""] + [args[-1]] def _generate_file_name() -> str: val: str = ( config["scene_names"][0] + "@" + datetime.now().strftime("%Y-%m-%d@%H-%M-%S") ) return val ================================================ FILE: manim/utils/iterables.py ================================================ """Operations on iterables.""" from __future__ import annotations __all__ = [ "adjacent_n_tuples", "adjacent_pairs", "all_elements_are_instances", "concatenate_lists", "list_difference_update", "list_update", "listify", "make_even", "make_even_by_cycling", "remove_list_redundancies", "remove_nones", "stretch_array_to_length", "tuplify", ] import itertools as it from collections.abc import ( Callable, Collection, Generator, Hashable, Iterable, Reversible, Sequence, ) from typing import TYPE_CHECKING, TypeVar, overload import numpy as np T = TypeVar("T") U = TypeVar("U") F = TypeVar("F", np.float64, np.int_) H = TypeVar("H", bound=Hashable) if TYPE_CHECKING: import numpy.typing as npt def adjacent_n_tuples(objects: Sequence[T], n: int) -> zip[tuple[T, ...]]: """Returns the Sequence objects cyclically split into n length tuples. See Also -------- adjacent_pairs : alias with n=2 Examples -------- .. code-block:: pycon >>> list(adjacent_n_tuples([1, 2, 3, 4], 2)) [(1, 2), (2, 3), (3, 4), (4, 1)] >>> list(adjacent_n_tuples([1, 2, 3, 4], 3)) [(1, 2, 3), (2, 3, 4), (3, 4, 1), (4, 1, 2)] """ return zip(*([*objects[k:], *objects[:k]] for k in range(n))) def adjacent_pairs(objects: Sequence[T]) -> zip[tuple[T, ...]]: """Alias for ``adjacent_n_tuples(objects, 2)``. See Also -------- adjacent_n_tuples Examples -------- .. code-block:: pycon >>> list(adjacent_pairs([1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4), (4, 1)] """ return adjacent_n_tuples(objects,
|
4), (3, 4, 1), (4, 1, 2)] """ return zip(*([*objects[k:], *objects[:k]] for k in range(n))) def adjacent_pairs(objects: Sequence[T]) -> zip[tuple[T, ...]]: """Alias for ``adjacent_n_tuples(objects, 2)``. See Also -------- adjacent_n_tuples Examples -------- .. code-block:: pycon >>> list(adjacent_pairs([1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4), (4, 1)] """ return adjacent_n_tuples(objects, 2) def all_elements_are_instances(iterable: Iterable[object], Class: type[object]) -> bool: """Returns ``True`` if all elements of iterable are instances of Class. False otherwise. """ return all(isinstance(e, Class) for e in iterable) def batch_by_property( items: Iterable[T], property_func: Callable[[T], U] ) -> list[tuple[list[T], U | None]]: """Takes in a Sequence, and returns a list of tuples, (batch, prop) such that all items in a batch have the same output when put into the Callable property_func, and such that chaining all these batches together would give the original Sequence (i.e. order is preserved). Examples -------- .. code-block:: pycon >>> batch_by_property([(1, 2), (3, 4), (5, 6, 7), (8, 9)], len) [([(1, 2), (3, 4)], 2), ([(5, 6, 7)], 3), ([(8, 9)], 2)] """ batch_prop_pairs: list[tuple[list[T], U | None]] = [] curr_batch: list[T] = [] curr_prop = None for item in items: prop = property_func(item) if prop != curr_prop: # Add current batch if len(curr_batch) > 0: batch_prop_pairs.append((curr_batch, curr_prop)) # Redefine curr curr_prop = prop curr_batch = [item] else: curr_batch.append(item) if len(curr_batch) > 0: batch_prop_pairs.append((curr_batch, curr_prop)) return batch_prop_pairs def concatenate_lists(*list_of_lists: Iterable[T]) -> list[T]: """Combines the Iterables provided as arguments into one list. Examples -------- .. code-block:: pycon >>> concatenate_lists([1, 2], [3, 4], [5]) [1, 2, 3, 4, 5] """ return [item for lst in list_of_lists for item in lst] def list_difference_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]: """Returns a list containing all the elements of l1 not in l2. Examples -------- .. code-block:: pycon >>> list_difference_update([1, 2, 3, 4], [2, 4]) [1, 3] """ return [e for e in l1 if e not in l2] def list_update(l1: Iterable[T], l2: Iterable[T]) -> list[T]: """Used instead of ``set.update()`` to maintain order, making sure duplicates are removed from l1, not l2. Removes overlap of l1 and l2 and then concatenates l2 unchanged. Examples -------- .. code-block:: pycon >>> list_update([1, 2, 3], [2, 4, 4]) [1, 3, 2, 4, 4] """ return [e for e in l1 if e not in l2] + list(l2) @overload def listify(obj: str) -> list[str]: ... @overload def listify(obj: Iterable[T]) -> list[T]: ... @overload def listify(obj: T) -> list[T]: ... def listify(obj: str | Iterable[T] | T) -> list[str] | list[T]: """Converts obj to a list intelligently. Examples -------- .. code-block:: pycon >>> listify("str") ['str'] >>> listify((1, 2)) [1, 2] >>> listify(len) [<built-in function len>] """ if isinstance(obj, str): return [obj] if isinstance(obj, Iterable): return list(obj) else: return [obj] def make_even( iterable_1: Iterable[T], iterable_2: Iterable[U] ) -> tuple[list[T], list[U]]: """Extends the shorter of the two iterables with duplicate values until its length is equal to the longer iterable (favours earlier elements). See Also -------- make_even_by_cycling : cycles elements instead of favouring earlier ones Examples -------- .. code-block:: pycon >>> make_even([1, 2], [3, 4, 5, 6]) ([1, 1,
|
tuple[list[T], list[U]]: """Extends the shorter of the two iterables with duplicate values until its length is equal to the longer iterable (favours earlier elements). See Also -------- make_even_by_cycling : cycles elements instead of favouring earlier ones Examples -------- .. code-block:: pycon >>> make_even([1, 2], [3, 4, 5, 6]) ([1, 1, 2, 2], [3, 4, 5, 6]) >>> make_even([1, 2], [3, 4, 5, 6, 7]) ([1, 1, 1, 2, 2], [3, 4, 5, 6, 7]) """ list_1, list_2 = list(iterable_1), list(iterable_2) len_list_1 = len(list_1) len_list_2 = len(list_2) length = max(len_list_1, len_list_2) return ( [list_1[(n * len_list_1) // length] for n in range(length)], [list_2[(n * len_list_2) // length] for n in range(length)], ) def make_even_by_cycling( iterable_1: Collection[T], iterable_2: Collection[U] ) -> tuple[list[T], list[U]]: """Extends the shorter of the two iterables with duplicate values until its length is equal to the longer iterable (cycles over shorter iterable). See Also -------- make_even : favours earlier elements instead of cycling them Examples -------- .. code-block:: pycon >>> make_even_by_cycling([1, 2], [3, 4, 5, 6]) ([1, 2, 1, 2], [3, 4, 5, 6]) >>> make_even_by_cycling([1, 2], [3, 4, 5, 6, 7]) ([1, 2, 1, 2, 1], [3, 4, 5, 6, 7]) """ length = max(len(iterable_1), len(iterable_2)) cycle1 = it.cycle(iterable_1) cycle2 = it.cycle(iterable_2) return ( [next(cycle1) for _ in range(length)], [next(cycle2) for _ in range(length)], ) def remove_list_redundancies(lst: Reversible[H]) -> list[H]: """Used instead of ``list(set(l))`` to maintain order. Keeps the last occurrence of each element. """ reversed_result = [] used = set() for x in reversed(lst): if x not in used: reversed_result.append(x) used.add(x) reversed_result.reverse() return reversed_result def remove_nones(sequence: Iterable[T | None]) -> list[T]: """Removes elements where bool(x) evaluates to False. Examples -------- .. code-block:: pycon >>> remove_nones(["m", "", "l", 0, 42, False, True]) ['m', 'l', 42, True] """ # Note this is redundant with it.chain return [x for x in sequence if x] def resize_array(nparray: npt.NDArray[F], length: int) -> npt.NDArray[F]: """Extends/truncates nparray so that ``len(result) == length``. The elements of nparray are cycled to achieve the desired length. See Also -------- resize_preserving_order : favours earlier elements instead of cycling them make_even_by_cycling : similar cycling behaviour for balancing 2 iterables Examples -------- .. code-block:: pycon >>> points = np.array([[1, 2], [3, 4]]) >>> resize_array(points, 1) array([[1, 2]]) >>> resize_array(points, 3) array([[1, 2], [3, 4], [1, 2]]) >>> resize_array(points, 2) array([[1, 2], [3, 4]]) """ if len(nparray) == length: return nparray return np.resize(nparray, (length, *nparray.shape[1:])) def resize_preserving_order( nparray: npt.NDArray[np.float64], length: int ) -> npt.NDArray[np.float64]: """Extends/truncates nparray so that ``len(result) == length``. The elements of nparray are duplicated to achieve the desired length (favours earlier elements). Constructs a zeroes array of length if nparray is empty. See Also -------- resize_array : cycles elements instead of favouring earlier ones make_even : similar earlier-favouring behaviour for balancing 2 iterables Examples -------- .. code-block:: pycon >>> resize_preserving_order(np.array([]), 5) array([0., 0., 0., 0., 0.]) >>> nparray = np.array([[1, 2], [3, 4]]) >>> resize_preserving_order(nparray, 1) array([[1, 2]]) >>> resize_preserving_order(nparray, 3) array([[1, 2], [1, 2], [3, 4]]) """ if len(nparray) == 0: return np.zeros((length, *nparray.shape[1:])) if len(nparray)
|
earlier-favouring behaviour for balancing 2 iterables Examples -------- .. code-block:: pycon >>> resize_preserving_order(np.array([]), 5) array([0., 0., 0., 0., 0.]) >>> nparray = np.array([[1, 2], [3, 4]]) >>> resize_preserving_order(nparray, 1) array([[1, 2]]) >>> resize_preserving_order(nparray, 3) array([[1, 2], [1, 2], [3, 4]]) """ if len(nparray) == 0: return np.zeros((length, *nparray.shape[1:])) if len(nparray) == length: return nparray indices = np.arange(length) * len(nparray) // length return nparray[indices] def resize_with_interpolation(nparray: npt.NDArray[F], length: int) -> npt.NDArray[F]: """Extends/truncates nparray so that ``len(result) == length``. New elements are interpolated to achieve the desired length. Note that if nparray's length changes, its dtype may too (e.g. int -> float: see Examples) See Also -------- resize_array : cycles elements instead of interpolating resize_preserving_order : favours earlier elements instead of interpolating Examples -------- .. code-block:: pycon >>> nparray = np.array([[1, 2], [3, 4]]) >>> resize_with_interpolation(nparray, 1) array([[1., 2.]]) >>> resize_with_interpolation(nparray, 4) array([[1. , 2. ], [1.66666667, 2.66666667], [2.33333333, 3.33333333], [3. , 4. ]]) >>> nparray = np.array([[[1, 2], [3, 4]]]) >>> nparray = np.array([[1, 2], [3, 4], [5, 6]]) >>> resize_with_interpolation(nparray, 4) array([[1. , 2. ], [2.33333333, 3.33333333], [3.66666667, 4.66666667], [5. , 6. ]]) >>> nparray = np.array([[1, 2], [3, 4], [1, 2]]) >>> resize_with_interpolation(nparray, 4) array([[1. , 2. ], [2.33333333, 3.33333333], [2.33333333, 3.33333333], [1. , 2. ]]) """ if len(nparray) == length: return nparray cont_indices = np.linspace(0, len(nparray) - 1, length) return np.array( [ (1 - a) * nparray[lh] + a * nparray[rh] for ci in cont_indices for lh, rh, a in [(int(ci), int(np.ceil(ci)), ci % 1)] ], ) def stretch_array_to_length(nparray: npt.NDArray[F], length: int) -> npt.NDArray[F]: # todo: is this the same as resize_preserving_order()? curr_len = len(nparray) if curr_len > length: raise Warning("Trying to stretch array to a length shorter than its own") indices = np.arange(length) / float(length) indices *= curr_len return nparray[indices.astype(int)] @overload def tuplify(obj: str) -> tuple[str]: ... @overload def tuplify(obj: Iterable[T]) -> tuple[T]: ... @overload def tuplify(obj: T) -> tuple[T]: ... def tuplify(obj: str | Iterable[T] | T) -> tuple[str] | tuple[T]: """Converts obj to a tuple intelligently. Examples -------- .. code-block:: pycon >>> tuplify("str") ('str',) >>> tuplify([1, 2]) (1, 2) >>> tuplify(len) (<built-in function len>,) """ if isinstance(obj, str): return (obj,) if isinstance(obj, Iterable): return tuple(obj) else: return (obj,) def uniq_chain(*args: Iterable[T]) -> Generator[T, None, None]: """Returns a generator that yields all unique elements of the Iterables provided via args in the order provided. Examples -------- .. code-block:: pycon >>> gen = uniq_chain([1, 2], [2, 3], [1, 4, 4]) >>> from collections.abc import Generator >>> isinstance(gen, Generator) True >>> tuple(gen) (1, 2, 3, 4) """ unique_items = set() for x in it.chain(*args): if x in unique_items: continue unique_items.add(x) yield x def hash_obj(obj: object) -> int: """Determines a hash, even of potentially mutable objects.""" if isinstance(obj, dict): return hash(tuple(sorted((hash_obj(k), hash_obj(v)) for k, v in obj.items()))) if isinstance(obj, set): return hash(tuple(sorted(hash_obj(e) for e in obj))) if isinstance(obj, (tuple, list)): return hash(tuple(hash_obj(e) for e in obj)) return hash(obj) ================================================ FILE: manim/utils/module_ops.py ================================================ from __future__ import annotations import importlib.util import inspect import re import sys import types import warnings from
|
return hash(tuple(sorted((hash_obj(k), hash_obj(v)) for k, v in obj.items()))) if isinstance(obj, set): return hash(tuple(sorted(hash_obj(e) for e in obj))) if isinstance(obj, (tuple, list)): return hash(tuple(hash_obj(e) for e in obj)) return hash(obj) ================================================ FILE: manim/utils/module_ops.py ================================================ from __future__ import annotations import importlib.util import inspect import re import sys import types import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, overload from manim._config import config, console, logger from manim.constants import ( CHOOSE_NUMBER_MESSAGE, INVALID_NUMBER_MESSAGE, NO_SCENE_MESSAGE, SCENE_NOT_FOUND_MESSAGE, ) from manim.scene.scene_file_writer import SceneFileWriter if TYPE_CHECKING: from manim.scene.scene import Scene __all__ = ["scene_classes_from_file"] def get_module(file_name: Path) -> types.ModuleType: if str(file_name) == "-": module = types.ModuleType("input_scenes") logger.info( "Enter the animation's code & end with an EOF (CTRL+D on Linux/Unix, CTRL+Z on Windows):", ) code = sys.stdin.read() if not code.startswith("from manim import"): logger.warning( "Didn't find an import statement for Manim. Importing automatically...", ) code = "from manim import *\n" + code logger.info("Rendering animation from typed code...") try: exec(code, module.__dict__) return module except Exception as e: logger.error(f"Failed to render scene: {str(e)}") sys.exit(2) else: if file_name.exists(): ext = file_name.suffix if ext != ".py": raise ValueError(f"{file_name} is not a valid Manim python script.") module_name = ".".join(file_name.with_suffix("").parts) warnings.filterwarnings( "default", category=DeprecationWarning, module=module_name, ) spec = importlib.util.spec_from_file_location(module_name, file_name) if isinstance(spec, importlib.machinery.ModuleSpec): module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module sys.path.insert(0, str(file_name.parent.absolute())) assert spec.loader spec.loader.exec_module(module) return module raise FileNotFoundError(f"{file_name} not found") else: raise FileNotFoundError(f"{file_name} not found") def get_scene_classes_from_module(module: types.ModuleType) -> list[type[Scene]]: from ..scene.scene import Scene def is_child_scene(obj: Any, module: types.ModuleType) -> bool: return ( inspect.isclass(obj) and issubclass(obj, Scene) and obj != Scene and obj.__module__.startswith(module.__name__) ) return [ member[1] for member in inspect.getmembers(module, lambda x: is_child_scene(x, module)) ] def get_scenes_to_render(scene_classes: list[type[Scene]]) -> list[type[Scene]]: if not scene_classes: logger.error(NO_SCENE_MESSAGE) return [] if config["write_all"]: return scene_classes result = [] for scene_name in config["scene_names"]: found = False for scene_class in scene_classes: if scene_class.__name__ == scene_name: result.append(scene_class) found = True break if not found and (scene_name != ""): logger.error(SCENE_NOT_FOUND_MESSAGE.format(scene_name)) if result: return result if len(scene_classes) == 1: config["scene_names"] = [scene_classes[0].__name__] return [scene_classes[0]] return prompt_user_for_choice(scene_classes) def prompt_user_for_choice(scene_classes: list[type[Scene]]) -> list[type[Scene]]: num_to_class = {} SceneFileWriter.force_output_as_scene_name = True for count, scene_class in enumerate(scene_classes, 1): name = scene_class.__name__ console.print(f"{count}: {name}", style="logging.level.info") num_to_class[count] = scene_class try: user_input = console.input( f"[log.message] {CHOOSE_NUMBER_MESSAGE} [/log.message]", ) scene_classes = [ num_to_class[int(num_str)] for num_str in re.split(r"\s*,\s*", user_input.strip()) ] config["scene_names"] = [scene_class.__name__ for scene_class in scene_classes] return scene_classes except KeyError: logger.error(INVALID_NUMBER_MESSAGE) sys.exit(2) except EOFError: sys.exit(1) except ValueError: logger.error("No scenes were selected. Exiting.") sys.exit(1) @overload def scene_classes_from_file( file_path: Path, require_single_scene: bool, full_list: Literal[True] ) -> list[type[Scene]]: ... @overload def scene_classes_from_file( file_path: Path, require_single_scene: Literal[True], full_list: Literal[False] = False, ) -> type[Scene]: ... @overload def scene_classes_from_file( file_path: Path, require_single_scene: Literal[False] = False, full_list: Literal[False] = False, ) -> list[type[Scene]]: ... def scene_classes_from_file( file_path: Path, require_single_scene: bool = False, full_list: bool = False ) -> type[Scene] | list[type[Scene]]: module = get_module(file_path) all_scene_classes = get_scene_classes_from_module(module) if full_list: return all_scene_classes scene_classes_to_render = get_scenes_to_render(all_scene_classes) if require_single_scene: assert len(scene_classes_to_render) == 1 return scene_classes_to_render[0] return scene_classes_to_render ================================================ FILE: manim/utils/opengl.py ================================================ from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import numpy.linalg as linalg from manim._config import config from
|
| list[type[Scene]]: module = get_module(file_path) all_scene_classes = get_scene_classes_from_module(module) if full_list: return all_scene_classes scene_classes_to_render = get_scenes_to_render(all_scene_classes) if require_single_scene: assert len(scene_classes_to_render) == 1 return scene_classes_to_render[0] return scene_classes_to_render ================================================ FILE: manim/utils/opengl.py ================================================ from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import numpy.linalg as linalg from manim._config import config from manim.typing import ManimFloat if TYPE_CHECKING: import numpy.typing as npt from typing_extensions import TypeAlias from manim.typing import MatrixMN, Point3D depth = 20 __all__ = [ "matrix_to_shader_input", "orthographic_projection_matrix", "perspective_projection_matrix", "translation_matrix", "x_rotation_matrix", "y_rotation_matrix", "z_rotation_matrix", "rotate_in_place_matrix", "rotation_matrix", "scale_matrix", "view_matrix", ] FlattenedMatrix4x4: TypeAlias = tuple[ float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, ] def matrix_to_shader_input(matrix: MatrixMN) -> FlattenedMatrix4x4: return tuple(matrix.T.ravel()) def orthographic_projection_matrix( width: float | None = None, height: float | None = None, near: float = 1, far: float = depth + 1, format_: bool = True, ) -> MatrixMN | FlattenedMatrix4x4: if width is None: width = config["frame_width"] if height is None: height = config["frame_height"] projection_matrix = np.array( [ [2 / width, 0, 0, 0], [0, 2 / height, 0, 0], [0, 0, -2 / (far - near), -(far + near) / (far - near)], [0, 0, 0, 1], ], ) if format_: return matrix_to_shader_input(projection_matrix) else: return projection_matrix def perspective_projection_matrix( width: float | None = None, height: float | None = None, near: float = 2, far: float = 50, format_: bool = True, ) -> MatrixMN | FlattenedMatrix4x4: if width is None: width = config["frame_width"] / 6 if height is None: height = config["frame_height"] / 6 projection_matrix = np.array( [ [2 * near / width, 0, 0, 0], [0, 2 * near / height, 0, 0], [0, 0, (far + near) / (near - far), (2 * far * near) / (near - far)], [0, 0, -1, 0], ], ) if format_: return matrix_to_shader_input(projection_matrix) else: return projection_matrix def translation_matrix(x: float = 0, y: float = 0, z: float = 0) -> MatrixMN: return np.array( [ [1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1], ], dtype=ManimFloat, ) def x_rotation_matrix(x: float = 0) -> MatrixMN: return np.array( [ [1, 0, 0, 0], [0, np.cos(x), -np.sin(x), 0], [0, np.sin(x), np.cos(x), 0], [0, 0, 0, 1], ], ) def y_rotation_matrix(y: float = 0) -> MatrixMN: return np.array( [ [np.cos(y), 0, np.sin(y), 0], [0, 1, 0, 0], [-np.sin(y), 0, np.cos(y), 0], [0, 0, 0, 1], ], ) def z_rotation_matrix(z: float = 0) -> MatrixMN: return np.array( [ [np.cos(z), -np.sin(z), 0, 0], [np.sin(z), np.cos(z), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ], ) # TODO: When rotating around the x axis, rotation eventually stops. def rotate_in_place_matrix( initial_position: Point3D, x: float = 0, y: float = 0, z: float = 0 ) -> MatrixMN: return np.matmul( translation_matrix(*-initial_position), np.matmul( rotation_matrix(x, y, z), translation_matrix(*initial_position), ), ) def rotation_matrix(x: float = 0, y: float = 0, z: float = 0) -> MatrixMN: return np.matmul( np.matmul(x_rotation_matrix(x), y_rotation_matrix(y)), z_rotation_matrix(z), ) def scale_matrix(scale_factor: float = 1) -> npt.NDArray: return np.array( [ [scale_factor, 0, 0, 0],
|
= 0 ) -> MatrixMN: return np.matmul( translation_matrix(*-initial_position), np.matmul( rotation_matrix(x, y, z), translation_matrix(*initial_position), ), ) def rotation_matrix(x: float = 0, y: float = 0, z: float = 0) -> MatrixMN: return np.matmul( np.matmul(x_rotation_matrix(x), y_rotation_matrix(y)), z_rotation_matrix(z), ) def scale_matrix(scale_factor: float = 1) -> npt.NDArray: return np.array( [ [scale_factor, 0, 0, 0], [0, scale_factor, 0, 0], [0, 0, scale_factor, 0], [0, 0, 0, 1], ], dtype=ManimFloat, ) def view_matrix( translation: Point3D | None = None, x_rotation: float = 0, y_rotation: float = 0, z_rotation: float = 0, ) -> MatrixMN: if translation is None: translation = np.array([0, 0, depth / 2 + 1]) model_matrix = np.matmul( np.matmul( translation_matrix(*translation), rotation_matrix(x=x_rotation, y=y_rotation, z=z_rotation), ), scale_matrix(), ) return tuple(linalg.inv(model_matrix).T.ravel()) ================================================ FILE: manim/utils/parameter_parsing.py ================================================ from __future__ import annotations from collections.abc import Iterable from types import GeneratorType from typing import TypeVar T = TypeVar("T") def flatten_iterable_parameters( args: Iterable[T | Iterable[T] | GeneratorType], ) -> list[T]: """Flattens an iterable of parameters into a list of parameters. Parameters ---------- args The iterable of parameters to flatten. [(generator), [], (), ...] Returns ------- :class:`list` The flattened list of parameters. """ flattened_parameters: list[T] = [] for arg in args: if isinstance(arg, (Iterable, GeneratorType)): flattened_parameters.extend(arg) else: flattened_parameters.append(arg) return flattened_parameters ================================================ FILE: manim/utils/paths.py ================================================ """Functions determining transformation paths between sets of points.""" from __future__ import annotations __all__ = [ "straight_path", "path_along_arc", "clockwise_path", "counterclockwise_path", ] from typing import TYPE_CHECKING import numpy as np from ..constants import OUT from ..utils.bezier import interpolate from ..utils.space_ops import normalize, rotation_matrix if TYPE_CHECKING: from manim.typing import ( PathFuncType, Point3D_Array, Point3DLike_Array, Vector3DLike, ) STRAIGHT_PATH_THRESHOLD = 0.01 def straight_path() -> PathFuncType: """Simplest path function. Each point in a set goes in a straight path toward its destination. Examples -------- .. manim :: StraightPathExample class StraightPathExample(Scene): def construct(self): colors = [RED, GREEN, BLUE] starting_points = VGroup( *[ Dot(LEFT + pos, color=color) for pos, color in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.straight_path(), run_time=2, ) ) self.wait() """ return interpolate def path_along_circles( arc_angle: float, circles_centers: Point3DLike_Array, axis: Vector3DLike = OUT ) -> PathFuncType: """This function transforms each point by moving it roughly along a circle, each with its own specified center. The path may be seen as each point smoothly changing its orbit from its starting position to its destination. Parameters ---------- arc_angle The angle each point traverses around the quasicircle. circles_centers The centers of each point's quasicircle to rotate around. axis The axis of rotation. Examples -------- .. manim :: PathAlongCirclesExample class PathAlongCirclesExample(Scene): def construct(self): colors = [RED, GREEN, BLUE] starting_points = VGroup( *[ Dot(LEFT + pos, color=color) for pos, color in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) circle_center = Dot(3 * LEFT) self.add(circle_center) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.path_along_circles( 2 * PI, circle_center.get_center() ),
|
in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) circle_center = Dot(3 * LEFT) self.add(circle_center) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.path_along_circles( 2 * PI, circle_center.get_center() ), run_time=3, ) ) self.wait() """ unit_axis = normalize(axis, fall_back=OUT) def path( start_points: Point3D_Array, end_points: Point3D_Array, alpha: float ) -> Point3D_Array: detransformed_end_points = circles_centers + np.dot( end_points - circles_centers, rotation_matrix(-arc_angle, unit_axis).T ) rot_matrix = rotation_matrix(alpha * arc_angle, unit_axis) return circles_centers + np.dot( interpolate(start_points, detransformed_end_points, alpha) - circles_centers, rot_matrix.T, ) return path def path_along_arc(arc_angle: float, axis: Vector3DLike = OUT) -> PathFuncType: """This function transforms each point by moving it along a circular arc. Parameters ---------- arc_angle The angle each point traverses around a circular arc. axis The axis of rotation. Examples -------- .. manim :: PathAlongArcExample class PathAlongArcExample(Scene): def construct(self): colors = [RED, GREEN, BLUE] starting_points = VGroup( *[ Dot(LEFT + pos, color=color) for pos, color in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.path_along_arc(TAU * 2 / 3), run_time=3, ) ) self.wait() """ if abs(arc_angle) < STRAIGHT_PATH_THRESHOLD: return straight_path() unit_axis = normalize(axis, fall_back=OUT) def path( start_points: Point3D_Array, end_points: Point3D_Array, alpha: float ) -> Point3D_Array: vects = end_points - start_points centers = start_points + 0.5 * vects if arc_angle != np.pi: centers += np.cross(unit_axis, vects / 2.0) / np.tan(arc_angle / 2) rot_matrix = rotation_matrix(alpha * arc_angle, unit_axis) return centers + np.dot(start_points - centers, rot_matrix.T) return path def clockwise_path() -> PathFuncType: """This function transforms each point by moving clockwise around a half circle. Examples -------- .. manim :: ClockwisePathExample class ClockwisePathExample(Scene): def construct(self): colors = [RED, GREEN, BLUE] starting_points = VGroup( *[ Dot(LEFT + pos, color=color) for pos, color in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.clockwise_path(), run_time=2, ) ) self.wait() """ return path_along_arc(-np.pi) def counterclockwise_path() -> PathFuncType: """This function transforms each point by moving counterclockwise around a half circle. Examples -------- .. manim :: CounterclockwisePathExample class CounterclockwisePathExample(Scene): def construct(self): colors = [RED, GREEN, BLUE] starting_points = VGroup( *[ Dot(LEFT + pos, color=color) for pos, color in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.counterclockwise_path(), run_time=2, ) ) self.wait() """ return path_along_arc(np.pi) def spiral_path(angle: float, axis: Vector3DLike = OUT) -> PathFuncType: """This function transforms each point by moving along a spiral to its destination. Parameters ---------- angle The angle each point traverses around a spiral. axis The axis of rotation. Examples -------- .. manim :: SpiralPathExample class SpiralPathExample(Scene): def construct(self): colors =
|
def spiral_path(angle: float, axis: Vector3DLike = OUT) -> PathFuncType: """This function transforms each point by moving along a spiral to its destination. Parameters ---------- angle The angle each point traverses around a spiral. axis The axis of rotation. Examples -------- .. manim :: SpiralPathExample class SpiralPathExample(Scene): def construct(self): colors = [RED, GREEN, BLUE] starting_points = VGroup( *[ Dot(LEFT + pos, color=color) for pos, color in zip([UP, DOWN, LEFT], colors) ] ) finish_points = VGroup( *[ Dot(RIGHT + pos, color=color) for pos, color in zip([ORIGIN, UP, DOWN], colors) ] ) self.add(starting_points) self.add(finish_points) for dot in starting_points: self.add(TracedPath(dot.get_center, stroke_color=dot.get_color())) self.wait() self.play( Transform( starting_points, finish_points, path_func=utils.paths.spiral_path(2 * TAU), run_time=5, ) ) self.wait() """ if abs(angle) < STRAIGHT_PATH_THRESHOLD: return straight_path() unit_axis = normalize(axis, fall_back=OUT) def path( start_points: Point3D_Array, end_points: Point3D_Array, alpha: float ) -> Point3D_Array: rot_matrix = rotation_matrix((alpha - 1) * angle, unit_axis) return start_points + alpha * np.dot(end_points - start_points, rot_matrix.T) return path ================================================ FILE: manim/utils/polylabel.py ================================================ #!/usr/bin/env python from __future__ import annotations from queue import PriorityQueue from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: from collections.abc import Sequence from manim.typing import ( Point2D, Point2D_Array, Point2DLike, Point2DLike_Array, Point3DLike_Array, ) class Polygon: """ Initializes the Polygon with the given rings. Parameters ---------- rings A sequence of points, where each sequence represents the rings of the polygon. Typically, multiple rings indicate holes in the polygon. """ def __init__(self, rings: Sequence[Point2DLike_Array]) -> None: np_rings: list[Point2D_Array] = [np.asarray(ring) for ring in rings] # Flatten Array csum = np.cumsum([ring.shape[0] for ring in np_rings]) self.array: Point2D_Array = np.concatenate(np_rings, axis=0) # Compute Boundary self.start: Point2D_Array = np.delete(self.array, csum - 1, axis=0) self.stop: Point2D_Array = np.delete(self.array, csum % csum[-1], axis=0) self.diff: Point2D_Array = np.delete( np.diff(self.array, axis=0), csum[:-1] - 1, axis=0 ) self.norm: Point2D_Array = self.diff / np.einsum( "ij,ij->i", self.diff, self.diff ).reshape(-1, 1) # Compute Centroid x, y = self.start[:, 0], self.start[:, 1] xr, yr = self.stop[:, 0], self.stop[:, 1] self.area: float = 0.5 * (np.dot(x, yr) - np.dot(xr, y)) if self.area: factor = x * yr - xr * y cx = np.sum((x + xr) * factor) / (6.0 * self.area) cy = np.sum((y + yr) * factor) / (6.0 * self.area) self.centroid = np.array([cx, cy]) def compute_distance(self, point: Point2DLike) -> float: """Compute the minimum distance from a point to the polygon.""" scalars = np.einsum("ij,ij->i", self.norm, point - self.start) clips = np.clip(scalars, 0, 1).reshape(-1, 1) d: float = np.min( np.linalg.norm(self.start + self.diff * clips - point, axis=1) ) return d if self.inside(point) else -d def _is_point_on_segment( self, x_point: float, y_point: float, x0: float, y0: float, x1: float, y1: float, ) -> bool: """ Check if a point is on the segment. The segment is defined by (x0, y0) to (x1, y1). """ if min(x0, x1) <= x_point <= max(x0, x1) and min(y0, y1) <= y_point <= max( y0, y1 ): dx = x1 - x0 dy = y1 - y0 cross = dx * (y_point - y0) - dy * (x_point - x0) return bool(np.isclose(cross, 0.0)) return False def _ray_crosses_segment( self, x_point: float, y_point: float, x0: float, y0: float,
|
x1) and min(y0, y1) <= y_point <= max( y0, y1 ): dx = x1 - x0 dy = y1 - y0 cross = dx * (y_point - y0) - dy * (x_point - x0) return bool(np.isclose(cross, 0.0)) return False def _ray_crosses_segment( self, x_point: float, y_point: float, x0: float, y0: float, x1: float, y1: float, ) -> bool: """ Check if a horizontal ray to the right from point (x_point, y_point) crosses the segment. The segment is defined by (x0, y0) to (x1, y1). """ if (y0 > y_point) != (y1 > y_point): slope = (x1 - x0) / (y1 - y0) x_intersect = slope * (y_point - y0) + x0 return bool(x_point < x_intersect) return False def inside(self, point: Point2DLike) -> bool: """ Check if a point is inside the polygon. Uses ray casting algorithm and checks boundary points consistently. """ point_x, point_y = point start_x, start_y = self.start[:, 0], self.start[:, 1] stop_x, stop_y = self.stop[:, 0], self.stop[:, 1] segment_count = len(start_x) for i in range(segment_count): if self._is_point_on_segment( point_x, point_y, start_x[i], start_y[i], stop_x[i], stop_y[i], ): return True crossings = 0 for i in range(segment_count): if self._ray_crosses_segment( point_x, point_y, start_x[i], start_y[i], stop_x[i], stop_y[i], ): crossings += 1 return crossings % 2 == 1 class Cell: """ A square in a mesh covering the :class:`~.Polygon` passed as an argument. Parameters ---------- c Center coordinates of the Cell. h Half-Size of the Cell. polygon :class:`~.Polygon` object for which the distance is computed. """ def __init__(self, c: Point2DLike, h: float, polygon: Polygon) -> None: self.c: Point2D = np.asarray(c) self.h = h self.d = polygon.compute_distance(self.c) self.p = self.d + self.h * np.sqrt(2) def __lt__(self, other: Cell) -> bool: return self.d < other.d def __gt__(self, other: Cell) -> bool: return self.d > other.d def __le__(self, other: Cell) -> bool: return self.d <= other.d def __ge__(self, other: Cell) -> bool: return self.d >= other.d def polylabel(rings: Sequence[Point3DLike_Array], precision: float = 0.01) -> Cell: """ Finds the pole of inaccessibility (the point that is farthest from the edges of the polygon) using an iterative grid-based approach. Parameters ---------- rings A list of lists, where each list is a sequence of points representing the rings of the polygon. Typically, multiple rings indicate holes in the polygon. precision The precision of the result (default is 0.01). Returns ------- Cell A Cell containing the pole of inaccessibility to a given precision. """ # Precompute Polygon Data np_rings: list[Point2D_Array] = [np.asarray(ring)[:, :2] for ring in rings] polygon = Polygon(np_rings) # Bounding Box mins = np.min(polygon.array, axis=0) maxs = np.max(polygon.array, axis=0) dims = maxs - mins s = np.min(dims) h = s / 2.0 # Initial Grid queue: PriorityQueue[Cell] = PriorityQueue() xv, yv = np.meshgrid(np.arange(mins[0], maxs[0], s), np.arange(mins[1], maxs[1], s)) for corner in np.vstack([xv.ravel(), yv.ravel()]).T: queue.put(Cell(corner + h, h, polygon)) # Initial Guess best = Cell(polygon.centroid, 0, polygon) bbox = Cell(mins + (dims / 2), 0, polygon) if bbox.d > best.d: best = bbox # While there are cells to consider... directions = np.array([[-1, -1], [1, -1], [-1, 1], [1, 1]]) while not
|
np.vstack([xv.ravel(), yv.ravel()]).T: queue.put(Cell(corner + h, h, polygon)) # Initial Guess best = Cell(polygon.centroid, 0, polygon) bbox = Cell(mins + (dims / 2), 0, polygon) if bbox.d > best.d: best = bbox # While there are cells to consider... directions = np.array([[-1, -1], [1, -1], [-1, 1], [1, 1]]) while not queue.empty(): cell = queue.get() if cell > best: best = cell # If a cell is promising, subdivide! if cell.p - best.d > precision: h = cell.h / 2.0 offsets = cell.c + directions * h queue.put(Cell(offsets[0], h, polygon)) queue.put(Cell(offsets[1], h, polygon)) queue.put(Cell(offsets[2], h, polygon)) queue.put(Cell(offsets[3], h, polygon)) return best ================================================ FILE: manim/utils/qhull.py ================================================ #!/usr/bin/env python from __future__ import annotations from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: from manim.typing import PointND, PointND_Array class QuickHullPoint: def __init__(self, coordinates: PointND_Array) -> None: self.coordinates = coordinates def __hash__(self) -> int: return hash(self.coordinates.tobytes()) def __eq__(self, other: object) -> bool: if not isinstance(other, QuickHullPoint): raise ValueError are_coordinates_equal: bool = np.array_equal( self.coordinates, other.coordinates ) return are_coordinates_equal class SubFacet: def __init__(self, coordinates: PointND_Array) -> None: self.coordinates = coordinates self.points = frozenset(QuickHullPoint(c) for c in coordinates) def __hash__(self) -> int: return hash(self.points) def __eq__(self, other: object) -> bool: if not isinstance(other, SubFacet): raise ValueError return self.points == other.points class Facet: def __init__(self, coordinates: PointND_Array, internal: PointND) -> None: self.coordinates = coordinates self.center: PointND = np.mean(coordinates, axis=0) self.normal = self.compute_normal(internal) self.subfacets = frozenset( SubFacet(np.delete(self.coordinates, i, axis=0)) for i in range(self.coordinates.shape[0]) ) def compute_normal(self, internal: PointND) -> PointND: centered = self.coordinates - self.center _, _, vh = np.linalg.svd(centered) normal: PointND = vh[-1, :] normal /= np.linalg.norm(normal) # If the normal points towards the internal point, flip it! if np.dot(normal, self.center - internal) < 0: normal *= -1 return normal def __hash__(self) -> int: return hash(self.subfacets) def __eq__(self, other: object) -> bool: if not isinstance(other, Facet): raise ValueError return self.subfacets == other.subfacets class Horizon: def __init__(self) -> None: self.facets: set[Facet] = set() self.boundary: list[SubFacet] = [] class QuickHull: """ QuickHull algorithm for constructing a convex hull from a set of points. Parameters ---------- tolerance A tolerance threshold for determining when points lie on the convex hull (default is 1e-5). Attributes ---------- facets List of facets considered. removed Set of internal facets that have been removed from the hull during the construction process. outside Dictionary mapping each facet to its outside points and eye point. neighbors Mapping of subfacets to their neighboring facets. Each subfacet links precisely two neighbors. unclaimed Points that have not yet been classified as inside or outside the current hull. internal An internal point (i.e., the center of the initial simplex) used as a reference during hull construction. tolerance The tolerance used to determine if points are considered outside the current hull. """ def __init__(self, tolerance: float = 1e-5) -> None: self.facets: list[Facet] = [] self.removed: set[Facet] = set() self.outside: dict[Facet, tuple[PointND_Array | None, PointND | None]] = {} self.neighbors: dict[SubFacet, set[Facet]] = {} self.unclaimed: PointND_Array | None = None self.internal: PointND | None = None self.tolerance = tolerance def initialize(self, points: PointND_Array) -> None:
|
tolerance: float = 1e-5) -> None: self.facets: list[Facet] = [] self.removed: set[Facet] = set() self.outside: dict[Facet, tuple[PointND_Array | None, PointND | None]] = {} self.neighbors: dict[SubFacet, set[Facet]] = {} self.unclaimed: PointND_Array | None = None self.internal: PointND | None = None self.tolerance = tolerance def initialize(self, points: PointND_Array) -> None: # Sample Points simplex = points[ np.random.choice(points.shape[0], points.shape[1] + 1, replace=False) ] self.unclaimed = points new_internal: PointND = np.mean(simplex, axis=0) self.internal = new_internal # Build Simplex for c in range(simplex.shape[0]): facet = Facet(np.delete(simplex, c, axis=0), internal=new_internal) self.classify(facet) self.facets.append(facet) # Attach Neighbors for f in self.facets: for sf in f.subfacets: self.neighbors.setdefault(sf, set()).add(f) def classify(self, facet: Facet) -> None: assert self.unclaimed is not None, ( "Call .initialize() before using .classify()." ) if not self.unclaimed.size: self.outside[facet] = (None, None) return # Compute Projections projections = (self.unclaimed - facet.center) @ facet.normal arg = np.argmax(projections) mask = projections > self.tolerance # Identify Eye and Outside Set eye = self.unclaimed[arg] if projections[arg] > self.tolerance else None outside = self.unclaimed[mask] self.outside[facet] = (outside, eye) self.unclaimed = self.unclaimed[~mask] def compute_horizon(self, eye: PointND, start_facet: Facet) -> Horizon: horizon = Horizon() self._recursive_horizon(eye, start_facet, horizon) return horizon def _recursive_horizon(self, eye: PointND, facet: Facet, horizon: Horizon) -> bool: visible = np.dot(facet.normal, eye - facet.center) > 0 if not visible: return False # If the eye is visible from the facet: # Label the facet as visible and cross each edge horizon.facets.add(facet) for subfacet in facet.subfacets: neighbor = (self.neighbors[subfacet] - {facet}).pop() # If the neighbor is not visible, then the edge shared must be on the boundary if neighbor not in horizon.facets and not self._recursive_horizon( eye, neighbor, horizon ): horizon.boundary.append(subfacet) return True def build(self, points: PointND_Array) -> None: num, dim = points.shape if (dim == 0) or (num < dim + 1): raise ValueError("Not enough points supplied to build Convex Hull!") if dim == 1: raise ValueError("The Convex Hull of 1D data is its min-max!") self.initialize(points) # This helps the type checker. assert self.unclaimed is not None assert self.internal is not None while True: updated = False for facet in self.facets: if facet in self.removed: continue outside, eye = self.outside[facet] if eye is not None: updated = True horizon = self.compute_horizon(eye, facet) for f in horizon.facets: points_to_append = self.outside[f][0] # TODO: is this always true? assert points_to_append is not None self.unclaimed = np.vstack((self.unclaimed, points_to_append)) self.removed.add(f) for sf in f.subfacets: self.neighbors[sf].discard(f) if self.neighbors[sf] == set(): del self.neighbors[sf] for sf in horizon.boundary: nf = Facet( np.vstack((sf.coordinates, eye)), internal=self.internal ) self.classify(nf) self.facets.append(nf) for nsf in nf.subfacets: self.neighbors.setdefault(nsf, set()).add(nf) if not updated: break ================================================ FILE: manim/utils/rate_functions.py ================================================ """A selection of rate functions, i.e., *speed curves* for animations. Please find a standard list at https://easings.net/. Here is a picture for the non-standard ones .. manim:: RateFuncExample :save_last_frame: class RateFuncExample(Scene): def construct(self): x = VGroup() for k, v in rate_functions.__dict__.items(): if "function" in str(v): if ( not k.startswith("__") and not k.startswith("sqrt") and not k.startswith("bezier") ): try: rate_func = v plot = ( ParametricFunction( lambda x: [x, rate_func(x), 0], t_range=[0, 1, .01], use_smoothing=False, color=YELLOW, ) .stretch_to_fit_width(1.5) .stretch_to_fit_height(1) ) plot_bg =
|
RateFuncExample(Scene): def construct(self): x = VGroup() for k, v in rate_functions.__dict__.items(): if "function" in str(v): if ( not k.startswith("__") and not k.startswith("sqrt") and not k.startswith("bezier") ): try: rate_func = v plot = ( ParametricFunction( lambda x: [x, rate_func(x), 0], t_range=[0, 1, .01], use_smoothing=False, color=YELLOW, ) .stretch_to_fit_width(1.5) .stretch_to_fit_height(1) ) plot_bg = SurroundingRectangle(plot).set_color(WHITE) plot_title = ( Text(rate_func.__name__, weight=BOLD) .scale(0.5) .next_to(plot_bg, UP, buff=0.1) ) x.add(VGroup(plot_bg, plot, plot_title)) except: # because functions `not_quite_there`, `function squish_rate_func` are not working. pass x.arrange_in_grid(cols=8) x.height = config.frame_height x.width = config.frame_width x.move_to(ORIGIN).scale(0.95) self.add(x) There are primarily 3 kinds of standard easing functions: #. Ease In - The animation has a smooth start. #. Ease Out - The animation has a smooth end. #. Ease In Out - The animation has a smooth start as well as smooth end. .. note:: The standard functions are not exported, so to use them you do something like this: rate_func=rate_functions.ease_in_sine On the other hand, the non-standard functions, which are used more commonly, are exported and can be used directly. .. manim:: RateFunctions1Example class RateFunctions1Example(Scene): def construct(self): line1 = Line(3*LEFT, 3*RIGHT).shift(UP).set_color(RED) line2 = Line(3*LEFT, 3*RIGHT).set_color(GREEN) line3 = Line(3*LEFT, 3*RIGHT).shift(DOWN).set_color(BLUE) dot1 = Dot().move_to(line1.get_left()) dot2 = Dot().move_to(line2.get_left()) dot3 = Dot().move_to(line3.get_left()) label1 = Tex("Ease In").next_to(line1, RIGHT) label2 = Tex("Ease out").next_to(line2, RIGHT) label3 = Tex("Ease In Out").next_to(line3, RIGHT) self.play( FadeIn(VGroup(line1, line2, line3)), FadeIn(VGroup(dot1, dot2, dot3)), Write(VGroup(label1, label2, label3)), ) self.play( MoveAlongPath(dot1, line1, rate_func=rate_functions.ease_in_sine), MoveAlongPath(dot2, line2, rate_func=rate_functions.ease_out_sine), MoveAlongPath(dot3, line3, rate_func=rate_functions.ease_in_out_sine), run_time=7 ) self.wait() """ from __future__ import annotations __all__ = [ "linear", "smooth", "smoothstep", "smootherstep", "smoothererstep", "rush_into", "rush_from", "slow_into", "double_smooth", "there_and_back", "there_and_back_with_pause", "running_start", "not_quite_there", "wiggle", "squish_rate_func", "lingering", "exponential_decay", ] from functools import wraps from math import sqrt from typing import Any, Protocol import numpy as np from manim.utils.simple_functions import sigmoid # TODO: rewrite this to use ParamSpec when Python 3.9 is out of life class RateFunction(Protocol): def __call__(self, t: float, *args: Any, **kwargs: Any) -> float: ... # This is a decorator that makes sure any function it's used on will # return 0 if t<0 and 1 if t>1. def unit_interval(function: RateFunction) -> RateFunction: @wraps(function) def wrapper(t: float, *args: Any, **kwargs: Any) -> float: if 0 <= t <= 1: return function(t, *args, **kwargs) elif t < 0: return 0 else: return 1 return wrapper # This is a decorator that makes sure any function it's used on will # return 0 if t<0 or t>1. def zero(function: RateFunction) -> RateFunction: @wraps(function) def wrapper(t: float, *args: Any, **kwargs: Any) -> float: if 0 <= t <= 1: return function(t, *args, **kwargs) else: return 0 return wrapper @unit_interval def linear(t: float) -> float: return t @unit_interval def smooth(t: float, inflection: float = 10.0) -> float: error = sigmoid(-inflection / 2) return min( max((sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error), 0), 1, ) @unit_interval def smoothstep(t: float) -> float: """Implementation of the 1st order SmoothStep sigmoid function. The 1st derivative (speed) is zero at the endpoints. https://en.wikipedia.org/wiki/Smoothstep """ return 3 * t**2 - 2 * t**3 @unit_interval def smootherstep(t: float) -> float: """Implementation of
|
/ (1 - 2 * error), 0), 1, ) @unit_interval def smoothstep(t: float) -> float: """Implementation of the 1st order SmoothStep sigmoid function. The 1st derivative (speed) is zero at the endpoints. https://en.wikipedia.org/wiki/Smoothstep """ return 3 * t**2 - 2 * t**3 @unit_interval def smootherstep(t: float) -> float: """Implementation of the 2nd order SmoothStep sigmoid function. The 1st and 2nd derivatives (speed and acceleration) are zero at the endpoints. https://en.wikipedia.org/wiki/Smoothstep """ return 6 * t**5 - 15 * t**4 + 10 * t**3 @unit_interval def smoothererstep(t: float) -> float: """Implementation of the 3rd order SmoothStep sigmoid function. The 1st, 2nd and 3rd derivatives (speed, acceleration and jerk) are zero at the endpoints. https://en.wikipedia.org/wiki/Smoothstep """ return 35 * t**4 - 84 * t**5 + 70 * t**6 - 20 * t**7 @unit_interval def rush_into(t: float, inflection: float = 10.0) -> float: return 2 * smooth(t / 2.0, inflection) @unit_interval def rush_from(t: float, inflection: float = 10.0) -> float: return 2 * smooth(t / 2.0 + 0.5, inflection) - 1 @unit_interval def slow_into(t: float) -> float: val: float = np.sqrt(1 - (1 - t) * (1 - t)) return val @unit_interval def double_smooth(t: float) -> float: if t < 0.5: return 0.5 * smooth(2 * t) else: return 0.5 * (1 + smooth(2 * t - 1)) @zero def there_and_back(t: float, inflection: float = 10.0) -> float: new_t = 2 * t if t < 0.5 else 2 * (1 - t) return smooth(new_t, inflection) @zero def there_and_back_with_pause(t: float, pause_ratio: float = 1.0 / 3) -> float: a = 2.0 / (1.0 - pause_ratio) if t < 0.5 - pause_ratio / 2: return smooth(a * t) elif t < 0.5 + pause_ratio / 2: return 1 else: return smooth(a - a * t) @unit_interval def running_start( t: float, pull_factor: float = -0.5, ) -> float: t2 = t * t t3 = t2 * t t4 = t3 * t t5 = t4 * t t6 = t5 * t mt = 1 - t mt2 = mt * mt mt3 = mt2 * mt mt4 = mt3 * mt # This is equivalent to creating a Bézier with [0, 0, pull_factor, pull_factor, 1, 1, 1] # and evaluating it at t. return ( 15 * t2 * mt4 * pull_factor + 20 * t3 * mt3 * pull_factor + 15 * t4 * mt2 + 6 * t5 * mt + t6 ) def not_quite_there( func: RateFunction = smooth, proportion: float = 0.7, ) -> RateFunction: def resul(t: float, *args: Any, **kwargs: Any) -> float: return proportion * func(t, *args, **kwargs) return result @zero def wiggle(t: float, wiggles: float = 2) -> float: val: float = np.sin(wiggles * np.pi * t) return there_and_back(t) * val def squish_rate_func( func: RateFunction, a: float = 0.4, b: float = 0.6, ) -> RateFunction: def result(t: float, *args: Any, **kwargs: Any) -> float: if a == b: return a if t < a: new_t = 0.0 elif t > b: new_t = 1.0 else: new_t
|
return there_and_back(t) * val def squish_rate_func( func: RateFunction, a: float = 0.4, b: float = 0.6, ) -> RateFunction: def result(t: float, *args: Any, **kwargs: Any) -> float: if a == b: return a if t < a: new_t = 0.0 elif t > b: new_t = 1.0 else: new_t = (t - a) / (b - a) return func(new_t, *args, **kwargs) return result # Stylistically, should this take parameters (with default values)? # Ultimately, the functionality is entirely subsumed by squish_rate_func, # but it may be useful to have a nice name for with nice default params for # "lingering", different from squish_rate_func's default params @unit_interval def lingering(t: float) -> float: def identity(t: float) -> float: return t # TODO: Isn't this just 0.8 * t? return squish_rate_func(identity, 0, 0.8)(t) @unit_interval def exponential_decay(t: float, half_life: float = 0.1) -> float: # The half-life should be rather small to minimize # the cut-off error at the end val: float = 1 - np.exp(-t / half_life) return val @unit_interval def ease_in_sine(t: float) -> float: val: float = 1 - np.cos((t * np.pi) / 2) return val @unit_interval def ease_out_sine(t: float) -> float: val: float = np.sin((t * np.pi) / 2) return val @unit_interval def ease_in_out_sine(t: float) -> float: val: float = -(np.cos(np.pi * t) - 1) / 2 return val @unit_interval def ease_in_quad(t: float) -> float: return t * t @unit_interval def ease_out_quad(t: float) -> float: return 1 - (1 - t) * (1 - t) @unit_interval def ease_in_out_quad(t: float) -> float: return 2 * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 2) / 2 @unit_interval def ease_in_cubic(t: float) -> float: return t * t * t @unit_interval def ease_out_cubic(t: float) -> float: return 1 - pow(1 - t, 3) @unit_interval def ease_in_out_cubic(t: float) -> float: return 4 * t * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 3) / 2 @unit_interval def ease_in_quart(t: float) -> float: return t * t * t * t @unit_interval def ease_out_quart(t: float) -> float: return 1 - pow(1 - t, 4) @unit_interval def ease_in_out_quart(t: float) -> float: return 8 * t * t * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 4) / 2 @unit_interval def ease_in_quint(t: float) -> float: return t * t * t * t * t @unit_interval def ease_out_quint(t: float) -> float: return 1 - pow(1 - t, 5) @unit_interval def ease_in_out_quint(t: float) -> float: return 16 * t * t * t * t * t if t < 0.5 else 1 - pow(-2 * t + 2, 5) / 2 @unit_interval def ease_in_expo(t: float) -> float: return 0 if t == 0 else pow(2, 10 * t - 10) @unit_interval def ease_out_expo(t: float) -> float: return 1 if t == 1 else 1 - pow(2, -10 * t) @unit_interval def ease_in_out_expo(t: float) -> float: if t == 0: return 0 elif t == 1:
|
-> float: return 0 if t == 0 else pow(2, 10 * t - 10) @unit_interval def ease_out_expo(t: float) -> float: return 1 if t == 1 else 1 - pow(2, -10 * t) @unit_interval def ease_in_out_expo(t: float) -> float: if t == 0: return 0 elif t == 1: return 1 elif t < 0.5: return pow(2, 20 * t - 10) / 2 else: return (2 - pow(2, -20 * t + 10)) / 2 @unit_interval def ease_in_circ(t: float) -> float: return 1 - sqrt(1 - pow(t, 2)) @unit_interval def ease_out_circ(t: float) -> float: return sqrt(1 - pow(t - 1, 2)) @unit_interval def ease_in_out_circ(t: float) -> float: return ( (1 - sqrt(1 - pow(2 * t, 2))) / 2 if t < 0.5 else (sqrt(1 - pow(-2 * t + 2, 2)) + 1) / 2 ) @unit_interval def ease_in_back(t: float) -> float: c1 = 1.70158 c3 = c1 + 1 return c3 * t * t * t - c1 * t * t @unit_interval def ease_out_back(t: float) -> float: c1 = 1.70158 c3 = c1 + 1 return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2) @unit_interval def ease_in_out_back(t: float) -> float: c1 = 1.70158 c2 = c1 * 1.525 return ( (pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2 if t < 0.5 else (pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2 ) @unit_interval def ease_in_elastic(t: float) -> float: c4 = (2 * np.pi) / 3 if t == 0: return 0 elif t == 1: return 1 else: val: float = -pow(2, 10 * t - 10) * np.sin((t * 10 - 10.75) * c4) return val @unit_interval def ease_out_elastic(t: float) -> float: c4 = (2 * np.pi) / 3 if t == 0: return 0 elif t == 1: return 1 else: val: float = pow(2, -10 * t) * np.sin((t * 10 - 0.75) * c4) + 1 return val @unit_interval def ease_in_out_elastic(t: float) -> float: c5 = (2 * np.pi) / 4.5 if t == 0: return 0 elif t == 1: return 1 elif t < 0.5: val: float = -(pow(2, 20 * t - 10) * np.sin((20 * t - 11.125) * c5)) / 2 return val else: val = (pow(2, -20 * t + 10) * np.sin((20 * t - 11.125) * c5)) / 2 + 1 return val @unit_interval def ease_in_bounce(t: float) -> float: return 1 - ease_out_bounce(1 - t) @unit_interval def ease_out_bounce(t: float) -> float: n1 = 7.5625 d1 = 2.75 if t < 1 / d1: return n1 * t * t elif t < 2 / d1: return n1 * (t - 1.5 / d1) * (t - 1.5 / d1) + 0.75 elif t < 2.5 / d1: return n1 * (t - 2.25 / d1) * (t - 2.25 / d1) + 0.9375
|
return n1 * t * t elif t < 2 / d1: return n1 * (t - 1.5 / d1) * (t - 1.5 / d1) + 0.75 elif t < 2.5 / d1: return n1 * (t - 2.25 / d1) * (t - 2.25 / d1) + 0.9375 else: return n1 * (t - 2.625 / d1) * (t - 2.625 / d1) + 0.984375 @unit_interval def ease_in_out_bounce(t: float) -> float: if t < 0.5: return (1 - ease_out_bounce(1 - 2 * t)) / 2 else: return (1 + ease_out_bounce(2 * t - 1)) / 2 ================================================ FILE: manim/utils/simple_functions.py ================================================ """A collection of simple functions.""" from __future__ import annotations __all__ = [ "binary_search", "choose", "clip", "sigmoid", ] from collections.abc import Callable from functools import lru_cache from typing import Any, Protocol, TypeVar import numpy as np from scipy import special def binary_search( function: Callable[[float], float], target: float, lower_bound: float, upper_bound: float, tolerance: float = 1e-4, ) -> float | None: """Searches for a value in a range by repeatedly dividing the range in half. To be more precise, performs numerical binary search to determine the input to ``function``, between the bounds given, that outputs ``target`` to within ``tolerance`` (default of 0.0001). Returns ``None`` if no input can be found within the bounds. Examples -------- Consider the polynomial :math:`x^2 + 3x + 1` where we search for a target value of :math:`11`. An exact solution is :math:`x = 2`. :: >>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5) >>> bool(abs(solution - 2) < 1e-4) True >>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5, tolerance=0.01) >>> bool(abs(solution - 2) < 0.01) True Searching in the interval :math:`[0, 5]` for a target value of :math:`71` does not yield a solution:: >>> binary_search(lambda x: x**2 + 3*x + 1, 71, 0, 5) is None True """ lh = lower_bound rh = upper_bound mh: float = np.mean(np.array([lh, rh])) while abs(rh - lh) > tolerance: mh = np.mean(np.array([lh, rh])) lx, mx, rx = (function(h) for h in (lh, mh, rh)) if lx == target: return lh if rx == target: return rh if lx <= target <= rx: if mx > target: rh = mh else: lh = mh elif lx > target > rx: lh, rh = rh, lh else: return None return mh @lru_cache(maxsize=10) def choose(n: int, k: int) -> int: r"""The binomial coefficient n choose k. :math:`\binom{n}{k}` describes the number of possible choices of :math:`k` elements from a set of :math:`n` elements. References ---------- - https://en.wikipedia.org/wiki/Combination - https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.comb.html """ value: int = special.comb(n, k, exact=True) return value class Comparable(Protocol): def __lt__(self, other: Any) -> bool: ... def __gt__(self, other: Any) -> bool: ... ComparableT = TypeVar("ComparableT", bound=Comparable) def clip(a: ComparableT, min_a: ComparableT, max_a: ComparableT) -> ComparableT: """Clips ``a`` to the interval [``min_a``, ``max_a``]. Accepts any comparable objects (i.e. those that support <, >). Returns ``a`` if it is between ``min_a`` and ``max_a``. Otherwise, whichever of ``min_a`` and ``max_a`` is closest. Examples --------
|
... ComparableT = TypeVar("ComparableT", bound=Comparable) def clip(a: ComparableT, min_a: ComparableT, max_a: ComparableT) -> ComparableT: """Clips ``a`` to the interval [``min_a``, ``max_a``]. Accepts any comparable objects (i.e. those that support <, >). Returns ``a`` if it is between ``min_a`` and ``max_a``. Otherwise, whichever of ``min_a`` and ``max_a`` is closest. Examples -------- :: >>> clip(15, 11, 20) 15 >>> clip('a', 'h', 'k') 'h' """ if a < min_a: return min_a elif a > max_a: return max_a return a def sigmoid(x: float) -> float: r"""Returns the output of the logistic function. The logistic function, a common example of a sigmoid function, is defined as :math:`\frac{1}{1 + e^{-x}}`. References ---------- - https://en.wikipedia.org/wiki/Sigmoid_function - https://en.wikipedia.org/wiki/Logistic_function """ value: float = 1.0 / (1 + np.exp(-x)) return value ================================================ FILE: manim/utils/sounds.py ================================================ """Sound-related utility functions.""" from __future__ import annotations __all__ = [ "get_full_sound_file_path", ] from typing import TYPE_CHECKING from .. import config from ..utils.file_ops import seek_full_path_from_defaults if TYPE_CHECKING: from pathlib import Path from manim.typing import StrPath # Still in use by add_sound() function in scene_file_writer.py def get_full_sound_file_path(sound_file_name: StrPath) -> Path: return seek_full_path_from_defaults( sound_file_name, default_dir=config.get_dir("assets_dir"), extensions=[".wav", ".mp3"], ) ================================================ FILE: manim/utils/space_ops.py ================================================ """Utility functions for two- and three-dimensional vectors.""" from __future__ import annotations import itertools as it from collections.abc import Callable, Sequence from typing import TYPE_CHECKING import numpy as np from mapbox_earcut import triangulate_float32 as earcut from scipy.spatial.transform import Rotation from manim.constants import DOWN, OUT, PI, RIGHT, TAU, UP from manim.utils.iterables import adjacent_pairs if TYPE_CHECKING: import numpy.typing as npt from manim.typing import ( ManimFloat, MatrixMN, Point2D_Array, Point3D, Point3DLike, Point3DLike_Array, PointND, PointNDLike_Array, Vector2D, Vector2D_Array, Vector3D, Vector3DLike, Vector3DLike_Array, ) __all__ = [ "quaternion_mult", "quaternion_from_angle_axis", "angle_axis_from_quaternion", "quaternion_conjugate", "rotate_vector", "thick_diagonal", "rotation_matrix", "rotation_about_z", "z_to_vector", "angle_of_vector", "angle_between_vectors", "normalize", "get_unit_normal", "compass_directions", "regular_vertices", "complex_to_R3", "R3_to_complex", "complex_func_to_R3_func", "center_of_mass", "midpoint", "find_intersection", "line_intersection", "get_winding_number", "shoelace", "shoelace_direction", "cross2d", "earclip_triangulation", "cartesian_to_spherical", "spherical_to_cartesian", "perpendicular_bisector", ] def norm_squared(v: float) -> float: val: float = np.dot(v, v) return val def cross(v1: Vector3DLike, v2: Vector3DLike) -> Vector3D: return np.array( [ v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0], ] ) # Quaternions # TODO, implement quaternion type def quaternion_mult( *quats: Sequence[float], ) -> np.ndarray | list[float | np.ndarray]: """Gets the Hamilton product of the quaternions provided. For more information, check `this Wikipedia page <https://en.wikipedia.org/wiki/Quaternion>`__. Returns ------- Union[np.ndarray, List[Union[float, np.ndarray]]] Returns a list of product of two quaternions. """ if len(quats) == 0: return [1, 0, 0, 0] result = quats[0] for next_quat in quats[1:]: w1, x1, y1, z1 = result w2, x2, y2, z2 = next_quat result = [ w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2, w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2, ] return result def quaternion_from_angle_axis( angle: float, axis: np.ndarray, axis_normalized: bool = False, ) -> list[float]: """Gets a quaternion from an angle and
|
+ y1 * w2 + z1 * x2 - x1 * z2, w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2, ] return result def quaternion_from_angle_axis( angle: float, axis: np.ndarray, axis_normalized: bool = False, ) -> list[float]: """Gets a quaternion from an angle and an axis. For more information, check `this Wikipedia page <https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles>`__. Parameters ---------- angle The angle for the quaternion. axis The axis for the quaternion axis_normalized Checks whether the axis is normalized, by default False Returns ------- list[float] Gives back a quaternion from the angle and axis """ if not axis_normalized: axis = normalize(axis) return [np.cos(angle / 2), *(np.sin(angle / 2) * axis)] def angle_axis_from_quaternion(quaternion: Sequence[float]) -> Sequence[float]: """Gets angle and axis from a quaternion. Parameters ---------- quaternion The quaternion from which we get the angle and axis. Returns ------- Sequence[float] Gives the angle and axis """ axis = normalize(quaternion[1:], fall_back=np.array([1, 0, 0])) angle = 2 * np.arccos(quaternion[0]) if angle > TAU / 2: angle = TAU - angle return angle, axis def quaternion_conjugate(quaternion: Sequence[float]) -> np.ndarray: """Used for finding the conjugate of the quaternion Parameters ---------- quaternion The quaternion for which you want to find the conjugate for. Returns ------- np.ndarray The conjugate of the quaternion. """ result = np.array(quaternion) result[1:] *= -1 return result def rotate_vector( vector: Vector3DLike, angle: float, axis: Vector3DLike = OUT ) -> Vector3D: """Function for rotating a vector. Parameters ---------- vector The vector to be rotated. angle The angle to be rotated by. axis The axis to be rotated, by default OUT Returns ------- np.ndarray The rotated vector with provided angle and axis. Raises ------ ValueError If vector is not of dimension 2 or 3. """ if len(vector) > 3: raise ValueError("Vector must have the correct dimensions.") if len(vector) == 2: vector = np.append(vector, 0) return rotation_matrix(angle, axis) @ vector def thick_diagonal(dim: int, thickness: int = 2) -> MatrixMN: 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 rotation_matrix_transpose_from_quaternion(quat: np.ndarray) -> list[np.ndarray]: """Converts the quaternion, quat, to an equivalent rotation matrix representation. For more information, check `this page <https://in.mathworks.com/help/driving/ref/quaternion.rotmat.html>`_. Parameters ---------- quat The quaternion which is to be converted. Returns ------- List[np.ndarray] Gives back the Rotation matrix representation, returned as a 3-by-3 matrix or 3-by-3-by-N multidimensional array. """ quat_inv = quaternion_conjugate(quat) return [ quaternion_mult(quat, [0, *basis], quat_inv)[1:] for basis in [ [1, 0, 0], [0, 1, 0], [0, 0, 1], ] ] def rotation_matrix_from_quaternion(quat: np.ndarray) -> np.ndarray: return np.transpose(rotation_matrix_transpose_from_quaternion(quat)) def rotation_matrix_transpose(angle: float, axis: Vector3DLike) -> np.ndarray: if all(np.array(axis)[:2] == np.zeros(2)): return rotation_about_z(angle * np.sign(axis[2])).T return rotation_matrix(angle, axis).T def rotation_matrix( angle: float, axis: Vector3DLike, homogeneous: bool = False, ) -> np.ndarray: """Rotation in R^3 about a specified axis of rotation.""" inhomogeneous_rotation_matrix = Rotation.from_rotvec( angle * normalize(axis) ).as_matrix() if not homogeneous: return inhomogeneous_rotation_matrix else: rotation_matrix = np.eye(4) rotation_matrix[:3, :3] = inhomogeneous_rotation_matrix return rotation_matrix def rotation_about_z(angle: float) -> np.ndarray: """Returns a rotation matrix for a given angle. Parameters ---------- angle Angle for the rotation matrix. Returns ------- np.ndarray Gives back the rotated matrix.
|
= Rotation.from_rotvec( angle * normalize(axis) ).as_matrix() if not homogeneous: return inhomogeneous_rotation_matrix else: rotation_matrix = np.eye(4) rotation_matrix[:3, :3] = inhomogeneous_rotation_matrix return rotation_matrix def rotation_about_z(angle: float) -> np.ndarray: """Returns a rotation matrix for a given angle. Parameters ---------- angle Angle for the rotation matrix. Returns ------- np.ndarray Gives back the rotated matrix. """ c, s = np.cos(angle), np.sin(angle) return np.array( [ [c, -s, 0], [s, c, 0], [0, 0, 1], ] ) def z_to_vector(vector: np.ndarray) -> np.ndarray: """ Returns some matrix in SO(3) which takes the z-axis to the (normalized) vector provided as an argument """ axis_z = normalize(vector) axis_y = normalize(cross(axis_z, RIGHT)) axis_x = cross(axis_y, axis_z) if np.linalg.norm(axis_y) == 0: # the vector passed just so happened to be in the x direction. axis_x = normalize(cross(UP, axis_z)) axis_y = -cross(axis_x, axis_z) return np.array([axis_x, axis_y, axis_z]).T def angle_of_vector(vector: Sequence[float] | np.ndarray) -> float: """Returns polar coordinate theta when vector is projected on xy plane. Parameters ---------- vector The vector to find the angle for. Returns ------- float The angle of the vector projected. """ if isinstance(vector, np.ndarray) and len(vector.shape) > 1: if vector.shape[0] < 2: raise ValueError("Vector must have the correct dimensions. (2, n)") c_vec = np.empty(vector.shape[1], dtype=np.complex128) c_vec.real = vector[0] c_vec.imag = vector[1] val1: float = np.angle(c_vec) return val1 val: float = np.angle(complex(*vector[:2])) return val def angle_between_vectors(v1: np.ndarray, v2: np.ndarray) -> float: """Returns the angle between two vectors. This angle will always be between 0 and pi Parameters ---------- v1 The first vector. v2 The second vector. Returns ------- float The angle between the vectors. """ val: float = 2 * np.arctan2( np.linalg.norm(normalize(v1) - normalize(v2)), np.linalg.norm(normalize(v1) + normalize(v2)), ) return val def normalize( vect: np.ndarray | tuple[float], fall_back: np.ndarray | None = None ) -> np.ndarray: norm = np.linalg.norm(vect) if norm > 0: return np.array(vect) / norm else: return fall_back or np.zeros(len(vect)) def normalize_along_axis(array: np.ndarray, axis: np.ndarray) -> np.ndarray: """Normalizes an array with the provided axis. Parameters ---------- array The array which has to be normalized. axis The axis to be normalized to. Returns ------- np.ndarray Array which has been normalized according to the axis. """ norms = np.sqrt((array * array).sum(axis)) norms[norms == 0] = 1 buffed_norms = np.repeat(norms, array.shape[axis]).reshape(array.shape) array /= buffed_norms return array def get_unit_normal(v1: Vector3DLike, v2: Vector3DLike, tol: float = 1e-6) -> Vector3D: """Gets the unit normal of the vectors. Parameters ---------- v1 The first vector. v2 The second vector tol [description], by default 1e-6 Returns ------- np.ndarray The normal of the two vectors. """ np_v1 = np.asarray(v1) np_v2 = np.asarray(v2) # Instead of normalizing v1 and v2, just divide by the greatest # of all their absolute components, which is just enough div1, div2 = max(np.abs(np_v1)), max(np.abs(np_v2)) if div1 == 0.0: if div2 == 0.0: return DOWN u = np_v2 / div2 elif div2 == 0.0: u = np_v1 / div1 else: # Normal scenario: v1 and v2 are both non-null u1, u2 = np_v1 / div1, np_v2 / div2 cp = cross(u1, u2) cp_norm = np.sqrt(norm_squared(cp)) if cp_norm > tol: return cp / cp_norm # Otherwise,
|
u = np_v2 / div2 elif div2 == 0.0: u = np_v1 / div1 else: # Normal scenario: v1 and v2 are both non-null u1, u2 = np_v1 / div1, np_v2 / div2 cp = cross(u1, u2) cp_norm = np.sqrt(norm_squared(cp)) if cp_norm > tol: return cp / cp_norm # Otherwise, v1 and v2 were aligned u = u1 # If you are here, you have an "unique", non-zero, unit-ish vector u # If it's also too aligned to the Z axis, just return DOWN if abs(u[0]) < tol and abs(u[1]) < tol: return DOWN # Otherwise rotate u in the plane it shares with the Z axis, # 90° TOWARDS the Z axis. This is done via (u x [0, 0, 1]) x u, # which gives [-xz, -yz, x²+y²] (slightly scaled as well) cp = np.array([-u[0] * u[2], -u[1] * u[2], u[0] * u[0] + u[1] * u[1]]) cp_norm = np.sqrt(n_squared(cp)) # Because the norm(u) == 0 case was filtered in the beginning, # there is no need to check if the norm of cp is 0 return cp / cp_norm ### def compass_directions(n: int = 4, start_vect: np.ndarray = RIGHT) -> np.ndarray: """Finds the cardinal directions using tau. Parameters ---------- n The amount to be rotated, by default 4 start_vect The direction for the angle to start with, by default RIGHT Returns ------- np.ndarray The angle which has been rotated. """ angle = TAU / n return np.array([rotate_vector(start_vect, k * angle) for k in range(n)]) def regular_vertices( n: int, *, radius: float = 1, start_angle: float | None = None ) -> tuple[np.ndarray, float]: """Generates regularly spaced vertices around a circle centered at the origin. Parameters ---------- n The number of vertices radius The radius of the circle that the vertices are placed on. start_angle The angle the vertices start at. If unspecified, for even ``n`` values, ``0`` will be used. For odd ``n`` values, 90 degrees is used. Returns ------- vertices : :class:`numpy.ndarray` The regularly spaced vertices. start_angle : :class:`float` The angle the vertices start at. """ if start_angle is None: start_angle = 0 if n % 2 == 0 else TAU / 4 start_vector = rotate_vector(RIGHT * radius, start_angle) vertices = compass_directions(n, start_vector) return vertices, start_angle def complex_to_R3(complex_num: complex) -> np.ndarray: return np.array((complex_num.real, complex_num.imag, 0)) def R3_to_complex(point: Sequence[float]) -> np.ndarray: return complex(*point[:2]) def complex_func_to_R3_func( complex_func: Callable[[complex], complex], ) -> Callable[[Point3DLike], Point3D]: return lambda p: complex_to_R3(complex_func(R3_to_complex(p))) def center_of_mass(points: PointNDLike_Array) -> PointND: """Gets the center of mass of the points in space. Parameters ---------- points The points to find the center of mass from. Returns ------- np.ndarray The center of mass of the points. """ return np.average(points, 0, np.ones(len(points))) def midpoint( point1: Sequence[float], point2: Sequence[float], ) -> float | np.ndarray: """Gets the midpoint of two points. Parameters ---------- point1 The first point. point2 The second point. Returns ------- Union[float, np.ndarray] The midpoint of the points """ return center_of_mass([point1, point2]) def line_intersection( line1: Sequence[np.ndarray], line2: Sequence[np.ndarray] ) -> np.ndarray: """Returns the intersection point of two lines, each defined by
|
| np.ndarray: """Gets the midpoint of two points. Parameters ---------- point1 The first point. point2 The second point. Returns ------- Union[float, np.ndarray] The midpoint of the points """ return center_of_mass([point1, point2]) def line_intersection( line1: Sequence[np.ndarray], line2: Sequence[np.ndarray] ) -> np.ndarray: """Returns the intersection point of two lines, each defined by a pair of distinct points lying on the line. Parameters ---------- line1 A list of two points that determine the first line. line2 A list of two points that determine the second line. Returns ------- np.ndarray The intersection points of the two lines which are intersecting. Raises ------ ValueError Error is produced if the two lines don't intersect with each other or if the coordinates don't lie on the xy-plane. """ if any(np.array([line1, line2])[:, :, 2].reshape(-1)): # checks for z coordinates != 0 raise ValueError("Coords must be in the xy-plane.") # algorithm from https://stackoverflow.com/a/42727584 padded = ( np.pad(np.array(i)[:, :2], ((0, 0), (0, 1)), constant_values=1) for i in (line1, line2) ) line1, line2 = (cross(*i) for i in padded) x, y, z = cross(line1, line2) if z == 0: raise ValueError( "The lines are parallel, there is no unique intersection point." ) return np.array([x / z, y / z, 0]) def find_intersection( p0s: Point3DLike_Array, v0s: Vector3DLike_Array, p1s: Point3DLike_Array, v1s: Vector3DLike_Array, threshold: float = 1e-5, ) -> list[Point3D]: """ 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 """ # algorithm from https://en.wikipedia.org/wiki/Skew_lines#Nearest_points result = [] for p0, v0, p1, v1 in zip(p0s, v0s, p1s, v1s): normal = cross(v1, cross(v0, v1)) denom = max(np.dot(v0, normal), threshold) result += [p0 + np.dot(p1 - p0, normal) / denom * v0] return result def get_winding_number(points: Sequence[np.ndarray]) -> float: """Determine the number of times a polygon winds around the origin. The orientation is measured mathematically positively, i.e., counterclockwise. Parameters ---------- points The vertices of the polygon being queried. Examples -------- >>> from manim import Square, get_winding_number >>> polygon = Square() >>> get_winding_number(polygon.get_vertices()) np.float64(1.0) >>> polygon.shift(2 * UP) Square >>> get_winding_number(polygon.get_vertices()) np.float64(0.0) """ total_angle: float = 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 val: float = total_angle / TAU return val def shoelace(x_y: Point2D_Array) -> float: """2D implementation of the shoelace formula. Returns ------- :class:`float` Returns signed area. """ x = x_y[:, 0] y = x_y[:, 1] val: float = np.trapz(y, x) return val def shoelace_direction(x_y: Point2D_Array) -> str: """ Uses the area determined by the shoelace method to determine whether the input set of points is directed clockwise or counterclockwise. Returns ------- :class:`str` Either ``"CW"`` or ``"CCW"``. """ area = shoelace(x_y) return "CW" if area > 0 else "CCW" def cross2d( a: Vector2D | Vector2D_Array, b: Vector2D | Vector2D_Array, ) -> ManimFloat | npt.NDArray[ManimFloat]: """Compute the
|
method to determine whether the input set of points is directed clockwise or counterclockwise. Returns ------- :class:`str` Either ``"CW"`` or ``"CCW"``. """ area = shoelace(x_y) return "CW" if area > 0 else "CCW" def cross2d( a: Vector2D | Vector2D_Array, b: Vector2D | Vector2D_Array, ) -> ManimFloat | npt.NDArray[ManimFloat]: """Compute the determinant(s) of the passed vector (sequences). Parameters ---------- a A vector or a sequence of vectors. b A vector or a sequence of vectors. Returns ------- Sequence[float] | float The determinant or sequence of determinants of the first two components of the specified vectors. Examples -------- .. code-block:: pycon >>> cross2d(np.array([1, 2]), np.array([3, 4])) np.int64(-2) >>> cross2d( ... np.array([[1, 2, 0], [1, 0, 0]]), ... np.array([[3, 4, 0], [0, 1, 0]]), ... ) array([-2, 1]) """ 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 earclip_triangulation(verts: np.ndarray, ring_ends: list) -> list: """Returns a list of indices giving a triangulation of a polygon, potentially with holes. Parameters ---------- verts verts is a numpy array of points. ring_ends ring_ends is a list of indices indicating where the ends of new paths are. Returns ------- list A list of indices giving a triangulation of a polygon. """ # First, connect all the rings so that the polygon # with holes is instead treated as a (very convex) # polygon with one edge. Do this by drawing connections # between rings close to each other rings = [list(range(e0, e1)) for e0, e1 in zip([0, *ring_ends], ring_ends)] attached_rings = rings[:1] detached_rings = rings[1:] loop_connections = {} while detached_rings: i_range, j_range = ( list( filter( # Ignore indices that are already being # used to draw some connection lambda i: i not in loop_connections, it.chain(*ring_group), ), ) for ring_group in (attached_rings, detached_rings) ) # Closest point on the attached rings to an estimated midpoint # of the detached rings tmp_j_vert = midpoint(verts[j_range[0]], verts[j_range[len(j_range) // 2]]) i = min(i_range, key=lambda i: norm_squared(verts[i] - tmp_j_vert)) # Closest point of the detached rings to the aforementioned # point of the attached rings j = min(j_range, key=lambda j: norm_squared(verts[i] - verts[j])) # Recalculate i based on new j i = min(i_range, key=lambda i: norm_squared(verts[i] - verts[j])) # Remember to connect the polygon at these points loop_connections[i] = j loop_connections[j] = i # Move the ring which j belongs to from the # attached list to the detached list new_ring = next( (ring for ring in detached_rings if ring[0] <= j < ring[-1]), None ) if new_ring is not None: detached_rings.remove(new_ring) attached_rings.append(new_ring) else: raise Exception("Could not find a ring to attach") # Setup linked list after: list[int] = [] end0 = 0 for end1 in ring_ends: after.extend(range(end0 + 1, end1)) after.append(end0) end0 = end1 # Find an ordering of indices walking around the polygon indices = [] i = 0 for _ in range(len(verts) + len(ring_ends) - 1): # starting = False if i in loop_connections: j = loop_connections[i] indices.extend([i, j]) i = after[j]
|
in ring_ends: after.extend(range(end0 + 1, end1)) after.append(end0) end0 = end1 # Find an ordering of indices walking around the polygon indices = [] i = 0 for _ in range(len(verts) + len(ring_ends) - 1): # starting = False if i in loop_connections: j = loop_connections[i] indices.extend([i, j]) i = after[j] else: indices.append(i) i = after[i] if i == 0: break meta_indices = earcut(verts[indices, :2], [len(indices)]) return [indices[mi] for mi in meta_indices] def cartesian_to_spherical(vec: Sequence[float]) -> np.ndarray: """Returns an array of numbers corresponding to each polar coordinate value (distance, phi, theta). Parameters ---------- vec A numpy array ``[x, y, z]``. """ norm = np.linalg.norm(vec) if norm == 0: return 0, 0, 0 r = norm phi = np.arccos(vec[2] / r) theta = np.arctan2(vec[1], vec[0]) return np.array([r, theta, phi]) def spherical_to_cartesian(spherical: Sequence[float]) -> np.ndarray: """Returns a numpy array ``[x, y, z]`` based on the spherical coordinates given. Parameters ---------- spherical A list of three floats that correspond to the following: r - The distance between the point and the origin. theta - The azimuthal angle of the point to the positive x-axis. phi - The vertical angle of the point to the positive z-axis. """ r, theta, phi = spherical return np.array( [ r * np.cos(theta) * np.sin(phi), r * np.sin(theta) * np.sin(phi), r * np.cos(phi), ], ) def perpendicular_bisector( line: Sequence[np.ndarray], norm_vector: Vector3D = OUT, ) -> Sequence[np.ndarray]: """Returns a list of two points that correspond to the ends of the perpendicular bisector of the two points given. Parameters ---------- line a list of two numpy array points (corresponding to the ends of a line). norm_vector the vector perpendicular to both the line given and the perpendicular bisector. Returns ------- list A list of two numpy array points that correspond to the ends of the perpendicular bisector """ p1 = line[0] p2 = line[1] direction = cross(p1 - p2, norm_vector) m = midpoint(p1, p2) return [m + direction, m - direction] ================================================ FILE: manim/utils/tex.py ================================================ """Utilities for processing LaTeX templates.""" from __future__ import annotations __all__ = [ "TexTemplate", ] import copy import re import warnings from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from typing_extensions import Self from manim.typing import StrPath _DEFAULT_PREAMBLE = r"""\usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb}""" _BEGIN_DOCUMENT = r"\begin{document}" _END_DOCUMENT = r"\end{document}" @dataclass(eq=True) class TexTemplate: """TeX templates are used to create ``Tex`` and ``MathTex`` objects.""" _body: str = field(default="", init=False) """A custom body, can be set from a file.""" tex_compiler: str = "latex" """The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``.""" description: str = "" """A description of the template""" output_format: str = ".dvi" """The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``.""" documentclass: str = r"\documentclass[preview]{standalone}" r"""The command defining the documentclass, e.g. ``\documentclass[preview]{standalone}``.""" preamble: str = _DEFAULT_PREAMBLE r"""The document's preamble, i.e. the part between ``\documentclass`` and ``\begin{document}``.""" placeholder_text: str = "YourTextHere" """Text in the document that will be replaced by the expression to be rendered.""" post_doc_commands: str = "" r"""Text (definitions, commands) to be inserted at right after
|
defining the documentclass, e.g. ``\documentclass[preview]{standalone}``.""" preamble: str = _DEFAULT_PREAMBLE r"""The document's preamble, i.e. the part between ``\documentclass`` and ``\begin{document}``.""" placeholder_text: str = "YourTextHere" """Text in the document that will be replaced by the expression to be rendered.""" post_doc_commands: str = "" r"""Text (definitions, commands) to be inserted at right after ``\begin{document}``, e.g. ``\boldmath``.""" @property def body(self) -> str: """The entire TeX template.""" return self._body or "\n".join( filter( None, [ self.documentclass, self.preamble, _BEGIN_DOCUMENT, self.post_doc_commands, self.placeholder_text, _END_DOCUMENT, ], ) ) @body.setter def body(self, value: str) -> None: self._body = value @classmethod def from_file(cls, file: StrPath = "tex_template.tex", **kwargs: Any) -> Self: """Create an instance by reading the content of a file. Using the ``add_to_preamble`` and ``add_to_document`` methods on this instance will have no effect, as the body is read from the file. """ instance = cls(**kwargs) instance.body = Path(file).read_text(encoding="utf-8") return instance def add_to_preamble(self, txt: str, prepend: bool = False) -> Self: r"""Adds text to the TeX template's preamble (e.g. definitions, packages). Text can be inserted at the beginning or at the end of the preamble. Parameters ---------- txt String containing the text to be added, e.g. ``\usepackage{hyperref}``. prepend Whether the text should be added at the beginning of the preamble, i.e. right after ``\documentclass``. Default is to add it at the end of the preamble, i.e. right before ``\begin{document}``. """ if self._body: warnings.warn( "This TeX template was created with a fixed body, trying to add text the preamble will have no effect.", UserWarning, stacklevel=2, ) if prepend: self.preamble = txt + "\n" + self.preamble else: self.preamble += "\n" + txt return self def add_to_document(self, txt: str) -> Self: r"""Adds text to the TeX template just after \begin{document}, e.g. ``\boldmath``. Parameters ---------- txt String containing the text to be added. """ if self._body: warnings.warn( "This TeX template was created with a fixed body, trying to add text the document will have no effect.", UserWarning, stacklevel=2, ) self.post_doc_commands += txt return self def get_texcode_for_expression(self, expression: str) -> str: r"""Inserts expression verbatim into TeX template. Parameters ---------- expression The string containing the expression to be typeset, e.g. ``$\sqrt{2}$`` Returns ------- :class:`str` LaTeX code based on current template, containing the given ``expression`` and ready for typesetting """ return self.body.replace(self.placeholder_text, expression) def get_texcode_for_expression_in_env( self, expression: str, environment: str ) -> str: r"""Inserts expression into TeX template wrapped in ``\begin{environment}`` and ``\end{environment}``. Parameters ---------- expression The string containing the expression to be typeset, e.g. ``$\sqrt{2}$``. environment The string containing the environment in which the expression should be typeset, e.g. ``align*``. Returns ------- :class:`str` LaTeX code based on template, containing the given expression inside its environment, ready for typesetting """ begin, end = _texcode_for_environment(environment) return self.body.replace( self.placeholder_text, "\n".join([begin, expression, end]) ) def copy(self) -> Self: """Create a deep copy of the TeX template instance.""" return copy.deepcopy(self) def _texcode_for_environment(environment: str) -> tuple[str, str]: r"""Processes the tex_environment string to return the correct ``\begin{environment}[extra]{extra}`` and ``\end{environment}`` strings. Parameters ---------- environment The tex_environment as a string. Acceptable formats include: ``{align*}``, ``align*``, ``{tabular}[t]{cccl}``, ``tabular}{cccl``, ``\begin{tabular}[t]{cccl}``. Returns ------- Tuple[:class:`str`, :class:`str`] A pair of strings representing
|
of the TeX template instance.""" return copy.deepcopy(self) def _texcode_for_environment(environment: str) -> tuple[str, str]: r"""Processes the tex_environment string to return the correct ``\begin{environment}[extra]{extra}`` and ``\end{environment}`` strings. Parameters ---------- environment The tex_environment as a string. Acceptable formats include: ``{align*}``, ``align*``, ``{tabular}[t]{cccl}``, ``tabular}{cccl``, ``\begin{tabular}[t]{cccl}``. Returns ------- Tuple[:class:`str`, :class:`str`] A pair of strings representing the opening and closing of the tex environment, e.g. ``\begin{tabular}{cccl}`` and ``\end{tabular}`` """ environment = environment.removeprefix(r"\begin").removeprefix("{") # The \begin command takes everything and closes with a brace begin = r"\begin{" + environment # If it doesn't end on } or ], assume missing } if not begin.endswith(("}", "]")): begin += "}" # While the \end command terminates at the first closing brace split_at_brace = re.split("}", environment, maxsplit=1) end = r"\end{" + split_at_brace[0] + "}" return begin, end ================================================ FILE: manim/utils/tex_file_writing.py ================================================ """Interface for writing, compiling, and converting ``.tex`` files. .. SEEALSO:: :mod:`.mobject.svg.tex_mobject` """ from __future__ import annotations import hashlib import re import subprocess import unicodedata from collections.abc import Generator, Iterable, Sequence from pathlib import Path from re import Match from typing import Any from manim.utils.tex import TexTemplate from .. import config, logger __all__ = ["tex_to_svg_file"] def tex_hash(expression: Any) -> str: id_str = str(expression) hasher = hashlib.sha256() hasher.update(id_str.encode()) # Truncating at 16 bytes for cleanliness return hasher.hexdigest()[:16] def tex_to_svg_file( expression: str, environment: str | None = None, tex_template: TexTemplate | None = None, ) -> Path: r"""Takes a tex expression and returns the svg version of the compiled tex Parameters ---------- expression String containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo`` environment The string containing the environment in which the expression should be typeset, e.g. ``align*`` tex_template Template class used to typesetting. If not set, use default template set via `config["tex_template"]` Returns ------- :class:`Path` Path to generated SVG file. """ if tex_template is None: tex_template = config["tex_template"] tex_file = generate_tex_file(expression, environment, tex_template) # check if svg already exists svg_file = tex_file.with_suffix(".svg") if svg_file.exists(): return svg_file dvi_file = compile_tex( tex_file, tex_template.tex_compiler, tex_template.output_format, ) svg_file = convert_to_svg(dvi_file, tex_template.output_format) if not config["no_latex_cleanup"]: delete_nonsvg_files() return svg_file def generate_tex_file( expression: str, environment: str | None = None, tex_template: TexTemplate | None = None, ) -> Path: r"""Takes a tex expression (and an optional tex environment), and returns a fully formed tex file ready for compilation. Parameters ---------- expression String containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo`` environment The string containing the environment in which the expression should be typeset, e.g. ``align*`` tex_template Template class used to typesetting. If not set, use default template set via `config["tex_template"]` Returns ------- :class:`Path` Path to generated TeX file """ if tex_template is None: tex_template = config["tex_template"] if environment is not None: output = tex_template.get_texcode_for_expression_in_env(expression, environment) else: output = tex_template.get_texcode_for_expression(expression) tex_dir = config.get_dir("tex_dir") if not tex_dir.exists(): tex_dir.mkdir() result = tex_dir / (tex_hash(output) + ".tex") if not result.exists(): logger.info( "Writing %(expression)s to %(path)s", {"expression": expression, "path": f"{result}"}, ) result.write_text(output, encoding="utf-8") return result def make_tex_compilation_command( tex_compiler: str, output_format: str, tex_file: Path, tex_dir: Path ) -> list[str]: """Prepares the TeX compilation command, i.e. the TeX compiler name
|
not tex_dir.exists(): tex_dir.mkdir() result = tex_dir / (tex_hash(output) + ".tex") if not result.exists(): logger.info( "Writing %(expression)s to %(path)s", {"expression": expression, "path": f"{result}"}, ) result.write_text(output, encoding="utf-8") return result def make_tex_compilation_command( tex_compiler: str, output_format: str, tex_file: Path, tex_dir: Path ) -> list[str]: """Prepares the TeX compilation command, i.e. the TeX compiler name and all necessary CLI flags. Parameters ---------- tex_compiler String containing the compiler to be used, e.g. ``pdflatex`` or ``lualatex`` output_format String containing the output format generated by the compiler, e.g. ``.dvi`` or ``.pdf`` tex_file File name of TeX file to be typeset. tex_dir Path to the directory where compiler output will be stored. Returns ------- :class:`list[str]` Compilation command according to given parameters """ if tex_compiler in {"latex", "pdflatex", "luatex", "lualatex"}: command = [ tex_compiler, "-interaction=batchmode", f"-output-format={output_format[1:]}", "-halt-on-error", f"-output-directory={tex_dir.as_posix()}", f"{tex_file.as_posix()}", ] elif tex_compiler == "xelatex": if output_format == ".xdv": outflag = ["-no-pdf"] elif output_format == ".pdf": outflag = [] else: raise ValueError("xelatex output is either pdf or xdv") command = [ "xelatex", *outflag, "-interaction=batchmode", "-halt-on-error", f"-output-directory={tex_dir.as_posix()}", f"{tex_file.as_posix()}", ] else: raise ValueError(f"Tex compiler {tex_compiler} unknown.") return command def insight_inputenc_error(matching: Match[str]) -> Generator[str]: code_point = chr(int(matching[1], 16)) name = unicodedata.name(code_point) yield f"TexTemplate does not support character '{name}' (U+{matching[1]})." yield "See the documentation for manim.mobject.svg.tex_mobject for details on using a custom TexTemplate." def insight_package_not_found_error(matching: Match[str]) -> Generator[str]: yield f"You do not have package {matching[1]} installed." yield f"Install {matching[1]} it using your LaTeX package manager, or check for typos." def compile_tex(tex_file: Path, tex_compiler: str, output_format: str) -> Path: """Compiles a tex_file into a .dvi or a .xdv or a .pdf Parameters ---------- tex_file File name of TeX file to be typeset. tex_compiler String containing the compiler to be used, e.g. ``pdflatex`` or ``lualatex`` output_format String containing the output format generated by the compiler, e.g. ``.dvi`` or ``.pdf`` Returns ------- :class:`Path` Path to generated output file in desired format (DVI, XDV or PDF). """ result = tex_file.with_suffix(output_format) tex_dir = config.get_dir("tex_dir") if not result.exists(): command = make_tex_compilation_command( tex_compiler, output_format, tex_file, tex_dir, ) cp = subprocess.run(command, stdout=subprocess.DEVNULL) if cp.returncode != 0: log_file = tex_file.with_suffix(".log") print_all_tex_errors(log_file, tex_compiler, tex_file) raise ValueError( f"{tex_compiler} error converting to" f" {output_format[1:]}. See log output above or" f" the log file: {log_file}", ) return result def convert_to_svg(dvi_file: Path, extension: str, page: int = 1) -> Path: """Converts a .dvi, .xdv, or .pdf file into an svg using dvisvgm. Parameters ---------- dvi_file File name of the input file to be converted. extension String containing the file extension and thus indicating the file type, e.g. ``.dvi`` or ``.pdf`` page Page to be converted if input file is multi-page. Returns ------- :class:`Path` Path to generated SVG file. """ result = dvi_file.with_suffix(".svg") if not result.exists(): command = [ "dvisvgm", *(["--pdf"] if extension == ".pdf" else []), f"--page={page}", "--no-fonts", "--verbosity=0", f"--output={result.as_posix()}", f"{dvi_file.as_posix()}", ] subprocess.run(command, stdout=subprocess.DEVNULL) # if the file does not exist now, this means conversion failed if not result.exists(): raise ValueError( f"Your installation does not support converting {dvi_file.suffix} files to SVG." f" Consider updating dvisvgm to at least version 2.4." f" If this does not solve the problem, please
|
f"--output={result.as_posix()}", f"{dvi_file.as_posix()}", ] subprocess.run(command, stdout=subprocess.DEVNULL) # if the file does not exist now, this means conversion failed if not result.exists(): raise ValueError( f"Your installation does not support converting {dvi_file.suffix} files to SVG." f" Consider updating dvisvgm to at least version 2.4." f" If this does not solve the problem, please refer to our troubleshooting guide at:" f" https://docs.manim.community/en/stable/faq/general.html#my-installation-" f"does-not-support-converting-pdf-to-svg-help", ) return result def delete_nonsvg_files(additional_endings: Iterable[str] = ()) -> None: """Deletes every file that does not have a suffix in ``(".svg", ".tex", *additional_endings)`` Parameters ---------- additional_endings Additional endings to whitelist """ tex_dir = config.get_dir("tex_dir") file_suffix_whitelist = {".svg", ".tex", *additional_endings} for f in tex_dir.iterdir(): if f.suffix not in file_suffix_whitelist: f.unlink() def print_all_tex_errors(log_file: Path, tex_compiler: str, tex_file: Path) -> None: if not log_file.exists(): raise RuntimeError( f"{tex_compiler} failed but did not produce a log file. " "Check your LaTeX installation.", ) with log_file.open(encoding="utf-8") as f: tex_compilation_log = f.readlines() error_indices = [ index for index, line in enumerate(tex_compilation_log) if line.startswith("!") ] if error_indices: with tex_file.open(encoding="utf-8") as f: tex = f.readlines() for error_index in error_indices: print_tex_error(tex_compilation_log, error_index, tex) LATEX_ERROR_INSIGHTS = [ ( r"inputenc Error: Unicode character (?:.*) \(U\+([0-9a-fA-F]+)\)", insight_inputenc_error, ), ( r"LaTeX Error: File `(.*?[clsty])' not found", insight_package_not_found_error, ), ] def print_tex_error( tex_compilation_log: Sequence[str], error_start_index: int, tex_source: Sequence[str], ) -> None: logger.error( f"LaTeX compilation error: {tex_compilation_log[error_start_index][2:]}", ) # TeX errors eventually contain a line beginning 'l.xxx` where xxx is the line number that caused the compilation # failure. This code finds the next such line after the error current error message line_of_tex_error = ( int( [ log_line for log_line in tex_compilation_log[error_start_index:] if log_line.startswith("l.") ][0] .split(" ")[0] .split(".")[1], ) - 1 ) # our tex error may be on a line outside our user input because of post-processing if line_of_tex_error >= len(tex_source): return None context = ["Context of error: \n"] if line_of_tex_error < 3: context += tex_source[: line_of_tex_error + 3] context[-4] = "-> " + context[-4] elif line_of_tex_error > len(tex_source) - 3: context += tex_source[line_of_tex_error - 1 :] context[1] = "-> " + context[1] else: context += tex_source[line_of_tex_error - 3 : line_of_tex_error + 3] context[-4] = "-> " + context[-4] context_joined = "".join(context) logger.error(context_joined) for insights in LATEX_ERROR_INSIGHTS: prob, get_insight = insights matching = re.search( prob, "".join(tex_compilation_log[error_start_index])[2:], ) if matching is not None: for insight in get_insight(matching): logger.info(insight) ================================================ FILE: manim/utils/tex_templates.py ================================================ """A library of LaTeX templates.""" from __future__ import annotations __all__ = [ "TexTemplateLibrary", "TexFontTemplates", ] from .tex import * # This file makes TexTemplateLibrary and TexFontTemplates available for use in manim Tex and MathTex objects. def _new_ams_template() -> TexTemplate: """Returns a simple Tex Template with only basic AMS packages""" preamble = r""" \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} """ return TexTemplate(preamble=preamble) """ Tex Template preamble used by original upstream 3b1b """ _3b1b_preamble = r""" \usepackage[english]{babel} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} \usepackage{setspace} \usepackage{tipa} \usepackage{relsize} \usepackage{textcomp} \usepackage{mathrsfs} \usepackage{calligra} \usepackage{wasysym} \usepackage{ragged2e} \usepackage{physics} \usepackage{xcolor} \usepackage{microtype} \DisableLigatures{encoding = *, family = * } \linespread{1} """ # TexTemplateLibrary # class TexTemplateLibrary: """ A collection of basic TeX template objects Examples -------- Normal usage as a value for the keyword argument tex_template of Tex()
|
\usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} \usepackage{setspace} \usepackage{tipa} \usepackage{relsize} \usepackage{textcomp} \usepackage{mathrsfs} \usepackage{calligra} \usepackage{wasysym} \usepackage{ragged2e} \usepackage{physics} \usepackage{xcolor} \usepackage{microtype} \DisableLigatures{encoding = *, family = * } \linespread{1} """ # TexTemplateLibrary # class TexTemplateLibrary: """ A collection of basic TeX template objects Examples -------- Normal usage as a value for the keyword argument tex_template of Tex() and MathTex() mobjects:: ``Tex("My TeX code", tex_template=TexTemplateLibrary.ctex)`` """ default = TexTemplate(preamble=_3b1b_preamble) """An instance of the default TeX template in manim""" threeb1b = TexTemplate(preamble=_3b1b_preamble) """ An instance of the default TeX template used by 3b1b """ ctex = TexTemplate( tex_compiler="xelatex", output_format=".xdv", preamble=_3b1b_preamble.replace( r"\DisableLigatures{encoding = *, family = * }", r"\usepackage[UTF8]{ctex}", ), ) """An instance of the TeX template used by 3b1b when using the use_ctex flag""" simple = _new_ams_template() """An instance of a simple TeX template with only basic AMS packages loaded""" # TexFontTemplates # # TexFontTemplates takes a font_id and returns the appropriate TexTemplate() # Usage: # my_tex_template = TexFontTemplates.font_id # # Note: not all of these will work out-of-the-box. # They may require specific fonts to be installed on the local system. # For example TexFontTemplates.comic_sans will only work if the Microsoft font 'Comic Sans' # is installed on the local system. # # More information on these templates, along with example output can be found at # http://jf.burnol.free.fr/showcase.html" # # # Choices for font_id are: # # american_typewriter : "American Typewriter" # antykwa : "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)" # apple_chancery : "Apple Chancery" # auriocus_kalligraphicus : "Auriocus Kalligraphicus (Symbol Greek)" # baskervald_adf_fourier : "Baskervald ADF witFourier" # baskerville_it : "Baskerville (Italic)" # biolinum : "Biolinum" # brushscriptx : "BrushScriptX-Italic (PX math and Greek)" # chalkboard_se : "Chalkboard SE" # chalkduster : "Chalkduster" # comfortaa : "Comfortaa" # comic_sans : "Comic Sans MS" # droid_sans : "Droid Sans" # droid_sans_it : "Droid Sans (Italic)" # droid_serif : "Droid Serif" # droid_serif_px_it : "Droid Serif (PX math symbols) (Italic)" # ecf_augie : "ECF Augie (Euler Greek)" # ecf_jd : "ECF JD (with TX fonts)" # ecf_skeetch : "ECF Skeetch (CM Greek)" # ecf_tall_paul : "ECF Tall Paul (with Symbol font)" # ecf_webster : "ECF Webster (with TX fonts)" # electrum_adf : "Electrum ADF (CM Greek)" # epigrafica : Epigrafica # fourier_utopia : "Fourier Utopia (Fourier upright Greek)" # french_cursive : "French Cursive (Euler Greek)" # gfs_bodoni : "GFS Bodoni" # gfs_didot : "GFS Didot (Italic)" # gfs_neoHellenic : "GFS NeoHellenic" # gnu_freesans_tx : "GNU FreeSerif (and TX fonts symbols)" # gnu_freeserif_freesans : "GNU FreeSerif and FreeSans" # helvetica_fourier_it : "Helvetica with Fourier (Italic)" # latin_modern_tw_it : "Latin Modern Typewriter Proportional (CM Greek) (Italic)" # latin_modern_tw : "Latin Modern Typewriter Proportional" # libertine : "Libertine" # libris_adf_fourier : "Libris ADF with Fourier" # minion_pro_myriad_pro : "Minion Pro and Myriad Pro (and TX fonts symbols)" # minion_pro_tx : "Minion Pro (and TX fonts symbols)" # new_century_schoolbook : "New Century Schoolbook (Symbol Greek)" # new_century_schoolbook_px : "New Century Schoolbook (Symbol Greek, PX math symbols)" # noteworthy_light : "Noteworthy Light" # palatino : "Palatino (Symbol Greek)" # papyrus :
|
Pro and Myriad Pro (and TX fonts symbols)" # minion_pro_tx : "Minion Pro (and TX fonts symbols)" # new_century_schoolbook : "New Century Schoolbook (Symbol Greek)" # new_century_schoolbook_px : "New Century Schoolbook (Symbol Greek, PX math symbols)" # noteworthy_light : "Noteworthy Light" # palatino : "Palatino (Symbol Greek)" # papyrus : "Papyrus" # romande_adf_fourier_it : "Romande ADF with Fourier (Italic)" # slitex : "SliTeX (Euler Greek)" # times_fourier_it : "Times with Fourier (Italic)" # urw_avant_garde : "URW Avant Garde (Symbol Greek)" # urw_zapf_chancery : "URW Zapf Chancery (CM Greek)" # venturis_adf_fourier_it : "Venturis ADF with Fourier (Italic)" # verdana_it : "Verdana (Italic)" # vollkorn_fourier_it : "Vollkorn with Fourier (Italic)" # vollkorn : "Vollkorn (TX fonts for Greek and math symbols)" # zapf_chancery : "Zapf Chancery" # ----------------------------------------------------------------------------------------- # # # # # # # # # # # Latin Modern Typewriter Proportional lmtp = _new_ams_template() lmtp.description = "Latin Modern Typewriter Proportional" lmtp.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[variablett]{lmodern} \renewcommand{\rmdefault}{\ttdefault} \usepackage[LGRgreek]{mathastext} \MTgreekfont{lmtt} % no lgr lmvtt, so use lgr lmtt \Mathastext \let\varepsilon\epsilon % only \varsigma in LGR """, ) # Fourier Utopia (Fourier upright Greek) fufug = _new_ams_template() fufug.description = "Fourier Utopia (Fourier upright Greek)" fufug.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[upright]{fourier} \usepackage{mathastext} """, ) # Droid Serif droidserif = _new_ams_template() droidserif.description = "Droid Serif" droidserif.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[default]{droidserif} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon """, ) # Droid Sans droidsans = _new_ams_template() droidsans.description = "Droid Sans" droidsans.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[default]{droidsans} \usepackage[LGRgreek]{mathastext} \let\varepsilon\epsilon """, ) # New Century Schoolbook (Symbol Greek) ncssg = _new_ams_template() ncssg.description = "New Century Schoolbook (Symbol Greek)" ncssg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{newcent} \usepackage[symbolgreek]{mathastext} \linespread{1.1} """, ) # French Cursive (Euler Greek) fceg = _new_ams_template() fceg.description = "French Cursive (Euler Greek)" fceg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[default]{frcursive} \usepackage[eulergreek,noplusnominus,noequal,nohbar,% nolessnomore,noasterisk]{mathastext} """, ) # Auriocus Kalligraphicus (Symbol Greek) aksg = _new_ams_template() aksg.description = "Auriocus Kalligraphicus (Symbol Greek)" aksg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{aurical} \renewcommand{\rmdefault}{AuriocusKalligraphicus} \usepackage[symbolgreek]{mathastext} """, ) # Palatino (Symbol Greek) palatinosg = _new_ams_template() palatinosg.description = "Palatino (Symbol Greek)" palatinosg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{palatino} \usepackage[symbolmax,defaultmathsizes]{mathastext} """, ) # Comfortaa comfortaa = _new_ams_template() comfortaa.description = "Comfortaa" comfortaa.add_to_preamble( r""" \usepackage[default]{comfortaa} \usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext} \let\varphi\phi \linespread{1.06} """, ) # ECF Augie (Euler Greek) ecfaugieeg = _new_ams_template() ecfaugieeg.description = "ECF Augie (Euler Greek)" ecfaugieeg.add_to_preamble( r""" \renewcommand\familydefault{fau} % emerald package \usepackage[defaultmathsizes,eulergreek]{mathastext} """, ) # Electrum ADF (CM Greek) electrumadfcm = _new_ams_template() electrumadfcm.description = "Electrum ADF (CM Greek)" electrumadfcm.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[LGRgreek,basic,defaultmathsizes]{mathastext} \usepackage[lf]{electrum} \Mathastext \let\varphi\phi """, ) # American Typewriter americantypewriter = _new_ams_template() americantypewriter.description = "American Typewriter" americantypewriter.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{American Typewriter} \usepackage[defaultmathsizes]{mathastext} """, ) americantypewriter.tex_compiler = "xelatex" americantypewriter.output_format = ".xdv" # Minion Pro and Myriad Pro (and TX fonts symbols) mpmptx = _new_ams_template() mpmptx.description = "Minion Pro and Myriad Pro (and TX fonts symbols)" mpmptx.add_to_preamble( r""" \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Minion Pro} \setsansfont[Mapping=tex-text,Scale=MatchUppercase]{Myriad Pro} \renewcommand\familydefault\sfdefault \usepackage[defaultmathsizes]{mathastext} \renewcommand\familydefault\rmdefault """, ) mpmptx.tex_compiler = "xelatex" mpmptx.output_format = ".xdv" # New Century Schoolbook (Symbol Greek, PX math symbols) ncssgpxm = _new_ams_template() ncssgpxm.description = "New Century Schoolbook (Symbol Greek, PX math symbols)" ncssgpxm.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage{newcent} \usepackage[symbolgreek,defaultmathsizes]{mathastext} \linespread{1.06} """, ) # Vollkorn (TX fonts for Greek and math symbols) vollkorntx = _new_ams_template() vollkorntx.description = "Vollkorn (TX fonts for Greek
|
# New Century Schoolbook (Symbol Greek, PX math symbols) ncssgpxm = _new_ams_template() ncssgpxm.description = "New Century Schoolbook (Symbol Greek, PX math symbols)" ncssgpxm.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage{newcent} \usepackage[symbolgreek,defaultmathsizes]{mathastext} \linespread{1.06} """, ) # Vollkorn (TX fonts for Greek and math symbols) vollkorntx = _new_ams_template() vollkorntx.description = "Vollkorn (TX fonts for Greek and math symbols)" vollkorntx.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{txfonts} \usepackage[upright]{txgreeks} \usepackage{vollkorn} \usepackage[defaultmathsizes]{mathastext} """, ) # Libertine libertine = _new_ams_template() libertine.description = "Libertine" libertine.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{libertine} \usepackage[greek=n]{libgreek} \usepackage[noasterisk,defaultmathsizes]{mathastext} """, ) # SliTeX (Euler Greek) slitexeg = _new_ams_template() slitexeg.description = "SliTeX (Euler Greek)" slitexeg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{tpslifonts} \usepackage[eulergreek,defaultmathsizes]{mathastext} \MTEulerScale{1.06} \linespread{1.2} """, ) # ECF Webster (with TX fonts) ecfwebstertx = _new_ams_template() ecfwebstertx.description = "ECF Webster (with TX fonts)" ecfwebstertx.add_to_preamble( r""" \usepackage{txfonts} \usepackage[upright]{txgreeks} \renewcommand\familydefault{fwb} % emerald package \usepackage{mathastext} \renewcommand{\int}{\intop\limits} \linespread{1.5} """, ) ecfwebstertx.add_to_document( r""" \mathversion{bold} """, ) # Romande ADF with Fourier (Italic) italicromandeadff = _new_ams_template() italicromandeadff.description = "Romande ADF with Fourier (Italic)" italicromandeadff.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{fourier} \usepackage{romande} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} \renewcommand{\itshape}{\swashstyle} """, ) # Apple Chancery applechancery = _new_ams_template() applechancery.description = "Apple Chancery" applechancery.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Apple Chancery} \usepackage[defaultmathsizes]{mathastext} """, ) applechancery.tex_compiler = "xelatex" applechancery.output_format = ".xdv" # Zapf Chancery zapfchancery = _new_ams_template() zapfchancery.description = "Zapf Chancery" zapfchancery.add_to_preamble( r""" \DeclareFontFamily{T1}{pzc}{} \DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{} \DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{} \usepackage{chancery} % = \renewcommand{\rmdefault}{pzc} \renewcommand\shapedefault\itdefault \renewcommand\bfdefault\mddefault \usepackage[defaultmathsizes]{mathastext} \linespread{1.05} """, ) # Verdana (Italic) italicverdana = _new_ams_template() italicverdana.description = "Verdana (Italic)" italicverdana.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Verdana} \usepackage[defaultmathsizes,italic]{mathastext} """, ) italicverdana.tex_compiler = "xelatex" italicverdana.output_format = ".xdv" # URW Zapf Chancery (CM Greek) urwzccmg = _new_ams_template() urwzccmg.description = "URW Zapf Chancery (CM Greek)" urwzccmg.add_to_preamble( r""" \usepackage[T1]{fontenc} \DeclareFontFamily{T1}{pzc}{} \DeclareFontShape{T1}{pzc}{mb}{it}{<->s*[1.2] pzcmi8t}{} \DeclareFontShape{T1}{pzc}{m}{it}{<->ssub * pzc/mb/it}{} \DeclareFontShape{T1}{pzc}{mb}{sl}{<->ssub * pzc/mb/it}{} \DeclareFontShape{T1}{pzc}{m}{sl}{<->ssub * pzc/mb/sl}{} \DeclareFontShape{T1}{pzc}{m}{n}{<->ssub * pzc/mb/it}{} \usepackage{chancery} \usepackage{mathastext} \linespread{1.05}""", ) urwzccmg.add_to_document( r""" \boldmath """, ) # Comic Sans MS comicsansms = _new_ams_template() comicsansms.description = "Comic Sans MS" comicsansms.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Comic Sans MS} \usepackage[defaultmathsizes]{mathastext} """, ) comicsansms.tex_compiler = "xelatex" comicsansms.output_format = ".xdv" # GFS Didot (Italic) italicgfsdidot = _new_ams_template() italicgfsdidot.description = "GFS Didot (Italic)" italicgfsdidot.add_to_preamble( r""" \usepackage[T1]{fontenc} \renewcommand\rmdefault{udidot} \usepackage[LGRgreek,defaultmathsizes,italic]{mathastext} \let\varphi\phi """, ) # Chalkduster chalkduster = _new_ams_template() chalkduster.description = "Chalkduster" chalkduster.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Chalkduster} \usepackage[defaultmathsizes]{mathastext} """, ) chalkduster.tex_compiler = "lualatex" chalkduster.output_format = ".pdf" # Minion Pro (and TX fonts symbols) mptx = _new_ams_template() mptx.description = "Minion Pro (and TX fonts symbols)" mptx.add_to_preamble( r""" \usepackage{txfonts} \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Minion Pro} \usepackage[defaultmathsizes]{mathastext} """, ) mptx.tex_compiler = "xelatex" mptx.output_format = ".xdv" # GNU FreeSerif and FreeSans gnufsfs = _new_ams_template() gnufsfs.description = "GNU FreeSerif and FreeSans" gnufsfs.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[ExternalLocation, Mapping=tex-text, BoldFont=FreeSerifBold, ItalicFont=FreeSerifItalic, BoldItalicFont=FreeSerifBoldItalic]{FreeSerif} \setsansfont[ExternalLocation, Mapping=tex-text, BoldFont=FreeSansBold, ItalicFont=FreeSansOblique, BoldItalicFont=FreeSansBoldOblique, Scale=MatchLowercase]{FreeSans} \renewcommand{\familydefault}{lmss} \usepackage[LGRgreek,defaultmathsizes,noasterisk]{mathastext} \renewcommand{\familydefault}{\sfdefault} \Mathastext \let\varphi\phi % no `var' phi in LGR encoding \renewcommand{\familydefault}{\rmdefault} """, ) gnufsfs.tex_compiler = "xelatex" gnufsfs.output_format = ".xdv" # GFS NeoHellenic gfsneohellenic = _new_ams_template() gfsneohellenic.description = "GFS NeoHellenic" gfsneohellenic.add_to_preamble( r""" \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{neohellenic} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} """, ) # ECF Tall Paul (with Symbol font) ecftallpaul = _new_ams_template() ecftallpaul.description = "ECF Tall Paul (with Symbol font)" ecftallpaul.add_to_preamble( r""" \DeclareFontFamily{T1}{ftp}{} \DeclareFontShape{T1}{ftp}{m}{n}{ <->s*[1.4] ftpmw8t }{} % increase size by factor 1.4 \renewcommand\familydefault{ftp} % emerald package \usepackage[symbol]{mathastext} \let\infty\inftypsy """, ) # Droid Sans (Italic) italicdroidsans = _new_ams_template() italicdroidsans.description = "Droid Sans (Italic)" italicdroidsans.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[default]{droidsans}
|
Symbol font) ecftallpaul = _new_ams_template() ecftallpaul.description = "ECF Tall Paul (with Symbol font)" ecftallpaul.add_to_preamble( r""" \DeclareFontFamily{T1}{ftp}{} \DeclareFontShape{T1}{ftp}{m}{n}{ <->s*[1.4] ftpmw8t }{} % increase size by factor 1.4 \renewcommand\familydefault{ftp} % emerald package \usepackage[symbol]{mathastext} \let\infty\inftypsy """, ) # Droid Sans (Italic) italicdroidsans = _new_ams_template() italicdroidsans.description = "Droid Sans (Italic)" italicdroidsans.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[default]{droidsans} \usepackage[LGRgreek,defaultmathsizes,italic]{mathastext} \let\varphi\phi """, ) # Baskerville (Italic) italicbaskerville = _new_ams_template() italicbaskerville.description = "Baskerville (Italic)" italicbaskerville.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Baskerville} \usepackage[defaultmathsizes,italic]{mathastext} """, ) italicbaskerville.tex_compiler = "xelatex" italicbaskerville.output_format = ".xdv" # ECF JD (with TX fonts) ecfjdtx = _new_ams_template() ecfjdtx.description = "ECF JD (with TX fonts)" ecfjdtx.add_to_preamble( r""" \usepackage{txfonts} \usepackage[upright]{txgreeks} \renewcommand\familydefault{fjd} % emerald package \usepackage{mathastext} """, ) ecfjdtx.add_to_document( r"""\mathversion{bold} """, ) # Antykwa Półtawskiego (TX Fonts for Greek and math symbols) aptxgm = _new_ams_template() aptxgm.description = "Antykwa Półtawskiego (TX Fonts for Greek and math symbols)" aptxgm.add_to_preamble( r""" \usepackage[OT4,OT1]{fontenc} \usepackage{txfontssepackage[upright]{txgreeks} \usepackage{antpolt} \usepackage[defaultmathsizes,nolessnomore]{mathastext} """, ) # Papyrus papyrus = _new_ams_template() papyrus.description = "Papyrus" papyrus.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Papyrus} \usepackage[defaultmathsizes]{mathastext} """, ) papyrus.tex_compiler = "xelatex" papyrus.output_format = ".xdv" # GNU FreeSerif (and TX fonts symbols) gnufstx = _new_ams_template() gnufstx.description = "GNU FreeSerif (and TX fonts symbols)" gnufstx.add_to_preamble( r""" \usepackage[no-math]{fontspec} \usepackage{txfonts} %\let\mathbb=\varmathbb \setmainfont[ExternalLocation, Mapping=tex-text, BoldFont=FreeSerifBold, ItalicFont=FreeSerifItalic, BoldItalicFont=FreeSerifBoldItalic]{FreeSerif} \usepackage[defaultmathsizes]{mathastext} """, ) gnufstx.tex_compiler = "xelatex" gnufstx.output_format = ".pdf" # ECF Skeetch (CM Greek) ecfscmg = _new_ams_template() ecfscmg.description = "ECF Skeetch (CM Greek)" ecfscmg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[T1]{fontenc} \DeclareFontFamily{T1}{fsk}{} \DeclareFontShape{T1}{fsk}{m}{n}{<->s*[1.315] fskmw8t}{} \renewcommand\rmdefault{fsk} \usepackage[noendash,defaultmathsizes,nohbar,defaultimath]{mathastext} """, ) # Latin Modern Typewriter Proportional (CM Greek) (Italic) italiclmtpcm = _new_ams_template() italiclmtpcm.description = "Latin Modern Typewriter Proportional (CM Greek) (Italic)" italiclmtpcm.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[variablett,nomath]{lmodern} \renewcommand{\familydefault}{\ttdefault} \usepackage[frenchmath]{mathastext} \linespread{1.08} """, ) # Baskervald ADF with Fourier baskervaldadff = _new_ams_template() baskervaldadff.description = "Baskervald ADF with Fourier" baskervaldadff.add_to_preamble( r""" \usepackage[upright]{fourier} \usepackage{baskervald} \usepackage[defaultmathsizes,noasterisk]{mathastext} """, ) # Droid Serif (PX math symbols) (Italic) italicdroidserifpx = _new_ams_template() italicdroidserifpx.description = "Droid Serif (PX math symbols) (Italic)" italicdroidserifpx.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{pxfonts} \usepackage[default]{droidserif} \usepackage[LGRgreek,defaultmathsizes,italic,basic]{mathastext} \let\varphi\phi """, ) # Biolinum biolinum = _new_ams_template() biolinum.description = "Biolinum" biolinum.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{libertine} \renewcommand{\familydefault}{\sfdefault} \usepackage[greek=n,biolinum]{libgreek} \usepackage[noasterisk,defaultmathsizes]{mathastext} """, ) # Vollkorn with Fourier (Italic) italicvollkornf = _new_ams_template() italicvollkornf.description = "Vollkorn with Fourier (Italic)" italicvollkornf.add_to_preamble( r""" \usepackage{fourier} \usepackage{vollkorn} \usepackage[italic,nohbar]{mathastext} """, ) # Chalkboard SE chalkboardse = _new_ams_template() chalkboardse.description = "Chalkboard SE" chalkboardse.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Chalkboard SE} \usepackage[defaultmathsizes]{mathastext} """, ) chalkboardse.tex_compiler = "xelatex" chalkboardse.output_format = ".xdv" # Noteworthy Light noteworthylight = _new_ams_template() noteworthylight.description = "Noteworthy Light" noteworthylight.add_to_preamble( r""" \usepackage[no-math]{fontspec} \setmainfont[Mapping=tex-text]{Noteworthy Light} \usepackage[defaultmathsizes]{mathastext} """, ) # Epigrafica epigrafica = _new_ams_template() epigrafica.description = "Epigrafica" epigrafica.add_to_preamble( r""" \usepackage[LGR,OT1]{fontenc} \usepackage{epigrafica} \usepackage[basic,LGRgreek,defaultmathsizes]{mathastext} \let\varphi\phi \linespread{1.2} """, ) # Libris ADF with Fourier librisadff = _new_ams_template() librisadff.description = "Libris ADF with Fourier" librisadff.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[upright]{fourier} \usepackage{libris} \renewcommand{\familydefault}{\sfdefault} \usepackage[noasterisk]{mathastext} """, ) # Venturis ADF with Fourier (Italic) italicvanturisadff = _new_ams_template() italicvanturisadff.description = "Venturis ADF with Fourier (Italic)" italicvanturisadff.add_to_preamble( r""" \usepackage{fourier} \usepackage[lf]{venturis} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} """, ) # GFS Bodoni gfsbodoni = _new_ams_template() gfsbodoni.description = "GFS Bodoni" gfsbodoni.add_to_preamble( r""" \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{bodoni} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} """, ) # BrushScriptX-Italic (PX math and Greek) brushscriptxpx = _new_ams_template() brushscriptxpx.description = "BrushScriptX-Italic (PX math and Greek)" brushscriptxpx.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{pxfonts} %\usepackage{pbsi} \renewcommand{\rmdefault}{pbsi} \renewcommand{\mddefault}{xl} \renewcommand{\bfdefault}{xl} \usepackage[defaultmathsizes,noasterisk]{mathastext} """, ) brushscriptxpx.add_to_document( r"""\boldmath """, ) brushscriptxpx.tex_compiler = "xelatex" brushscriptxpx.output_format = ".xdv" #
|
= "GFS Bodoni" gfsbodoni.add_to_preamble( r""" \usepackage[T1]{fontenc} \renewcommand{\rmdefault}{bodoni} \usepackage[LGRgreek]{mathastext} \let\varphi\phi \linespread{1.06} """, ) # BrushScriptX-Italic (PX math and Greek) brushscriptxpx = _new_ams_template() brushscriptxpx.description = "BrushScriptX-Italic (PX math and Greek)" brushscriptxpx.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{pxfonts} %\usepackage{pbsi} \renewcommand{\rmdefault}{pbsi} \renewcommand{\mddefault}{xl} \renewcommand{\bfdefault}{xl} \usepackage[defaultmathsizes,noasterisk]{mathastext} """, ) brushscriptxpx.add_to_document( r"""\boldmath """, ) brushscriptxpx.tex_compiler = "xelatex" brushscriptxpx.output_format = ".xdv" # URW Avant Garde (Symbol Greek) urwagsg = _new_ams_template() urwagsg.description = "URW Avant Garde (Symbol Greek)" urwagsg.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage{avant} \renewcommand{\familydefault}{\sfdefault} \usepackage[symbolgreek,defaultmathsizes]{mathastext} """, ) # Times with Fourier (Italic) italictimesf = _new_ams_template() italictimesf.description = "Times with Fourier (Italic)" italictimesf.add_to_preamble( r""" \usepackage{fourier} \renewcommand{\rmdefault}{ptm} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} """, ) # Helvetica with Fourier (Italic) italichelveticaf = _new_ams_template() italichelveticaf.description = "Helvetica with Fourier (Italic)" italichelveticaf.add_to_preamble( r""" \usepackage[T1]{fontenc} \usepackage[scaled]{helvet} \usepackage{fourier} \renewcommand{\rmdefault}{phv} \usepackage[italic,defaultmathsizes,noasterisk]{mathastext} """, ) class TexFontTemplates: """ A collection of TeX templates for the fonts described at http://jf.burnol.free.fr/showcase.html These templates are specifically designed to allow you to typeset formulae and mathematics using different fonts. They are based on the mathastext LaTeX package. Examples --------- Normal usage as a value for the keyword argument tex_template of Tex() and MathTex() mobjects:: ``Tex("My TeX code", tex_template=TexFontTemplates.comic_sans)`` Notes ------ Many of these templates require that specific fonts are installed on your local machine. For example, choosing the template TexFontTemplates.comic_sans will not compile if the Comic Sans Microsoft font is not installed. To experiment, try to render the TexFontTemplateLibrary example scene: ``manim path/to/manim/example_scenes/advanced_tex_fonts.py TexFontTemplateLibrary -p -ql`` """ american_typewriter = americantypewriter """American Typewriter""" antykwa = aptxgm """Antykwa Półtawskiego (TX Fonts for Greek and math symbols)""" apple_chancery = applechancery """Apple Chancery""" auriocus_kalligraphicus = aksg """Auriocus Kalligraphicus (Symbol Greek)""" baskervald_adf_fourier = baskervaldadff """Baskervald ADF with Fourier""" baskerville_it = italicbaskerville """Baskerville (Italic)""" biolinum = biolinum """Biolinum""" brushscriptx brushscriptxpx """BrushScriptX-Italic (PX math and Greek)""" chalkboard_se = chalkboardse """Chalkboard SE""" chalkduster = chalkduster """Chalkduster""" comfortaa = comfortaa """Comfortaa""" comic_sans = comicsansms """Comic Sans MS""" droid_sans = droidsans """Droid Sans""" droid_sans_it = italicdroidsans """Droid Sans (Italic)""" droid_serif = droidserif """Droid Serif""" droid_serif_px_it = italicdroidserifpx """Droid Serif (PX math symbols) (Italic)""" ecf_augie = ecfaugieeg """ECF Augie (Euler Greek)""" ecf_jd = ecfjdtx """ECF JD (with TX fonts)""" ecf_skeetch = ecfscmg """ECF Skeetch (CM Greek)""" ecf_tall_paul = ecftallpaul """ECF Tall Paul (with Symbol font)""" ecf_webster = ecfwebstertx """ECF Webster (with TX fonts)""" electrum_adf = electrumadfcm """Electrum ADF (CM Greek)""" epigrafica = epigrafica """ Epigrafica """ fourier_utopia = fufug """Fourier Utopia (Fourier upright Greek)""" french_cursive = fceg """French Cursive (Euler Greek)""" gfs_bodoni = gfsbodoni """GFS Bodoni""" gfs_didot = italicgfsdidot """GFS Didot (Italic)""" gfs_neoHellenic = gfsneohellenic """GFS NeoHellenic""" gnu_freesans_tx = gnufstx """GNU FreeSerif (and TX fonts symbols)""" gnu_freeserif_freesans = gnufsfs """GNU FreeSerif and FreeSans""" helvetica_fourier_it = italichelveticaf """Helvetica with Fourier (Italic)""" latin_modern_tw_it = italiclmtpcm """Latin Modern Typewriter Proportional (CM Greek) (Italic)""" latin_modern_tw = lmtp """Latin Modern Typewriter Proportional""" libertine = libertine """Libertine""" libris_adf_fourier = librisadff """Libris ADF with Fourier""" minion_pro_myriad_pro = mpmptx """Minion Pro and Myriad Pro (and TX fonts symbols)""" minion_pro_tx = mptx """Minion Pro (and TX fonts symbols)""" new_century_schoolbook = ncssg """New Century Schoolbook (Symbol Greek)""" new_century_schoolbook_px = ncssgpxm """New Century Schoolbook (Symbol Greek, PX math symbols)""" noteworthy_light = noteworthylight """Noteworthy Light"""
|
librisadff """Libris ADF with Fourier""" minion_pro_myriad_pro = mpmptx """Minion Pro and Myriad Pro (and TX fonts symbols)""" minion_pro_tx = mptx """Minion Pro (and TX fonts symbols)""" new_century_schoolbook = ncssg """New Century Schoolbook (Symbol Greek)""" new_century_schoolbook_px = ncssgpxm """New Century Schoolbook (Symbol Greek, PX math symbols)""" noteworthy_light = noteworthylight """Noteworthy Light""" palatino = palatinosg """Palatino (Symbol Greek)""" papyrus = papyrus """Papyrus""" romande_adf_fourier_it = italicromandeadff """Romande ADF with Fourier (Italic)""" slitex = slitexeg """SliTeX (Euler Greek)""" times_fourier_it = italictimesf """Times with Fourier (Italic)""" urw_avant_garde = urwagsg """URW Avant Garde (Symbol Greek)""" urw_zapf_chancery = urwzccmg """URW Zapf Chancery (CM Greek)""" venturis_adf_fourier_it = italicvanturisadff """Venturis ADF with Fourier (Italic)""" verdana_it = italicverdana """Verdana (Italic)""" vollkorn_fourier_it = italicvollkornf """Vollkorn with Fourier (Italic)""" vollkorn = vollkorntx """Vollkorn (TX fonts for Greek and math symbols)""" zapf_chancery = zapfchancery """Zapf Chancery""" ================================================ FILE: manim/utils/unit.py ================================================ """Implement the Unit class.""" from __future__ import annotations import numpy as np from .. import config, constants from ..typing import Vector3D __all__ = ["Pixels", "Degrees", "Munits", "Percent"] class _PixelUnits: def __mul__(self, val: float) -> float: return val * config.frame_width / config.pixel_width def __rmul__(self, val: float) -> float: return val * config.frame_width / config.pixel_width class Percent: def __init__(self, axis: Vector3D) -> None: if np.array_equal(axis, constants.X_AXIS): self.length = config.frame_width if np.array_equal(axis, constants.Y_AXIS): self.length = config.frame_height if np.array_equal(axis, constants.Z_AXIS): raise NotImplementedError("length of Z axis is undefined") def __mul__(self, val: float) -> float: return val / 100 * self.length def __rmul__(self, val: float) -> float: return val / 100 * self.length Pixels = _PixelUnits() Degrees = constants.PI / 180 Munits = 1 ================================================ FILE: manim/utils/color/__init__.py ================================================ """Utilities for working with colors and predefined color constants. Color data structure -------------------- .. autosummary:: :toctree: ../reference core Predefined colors ----------------- There are several predefined colors available in Manim: - The colors listed in :mod:`.color.manim_colors` are loaded into Manim's global name space. - The colors in :mod:`.color.AS2700`, :mod:`.color.BS381`, :mod:`.color.DVIPSNAMES`, :mod:`.color.SVGNAMES`, :mod:`.color.X11` and :mod:`.color.XKCD` need to be accessed via their module (which are available in Manim's global name space), or imported separately. For example: .. code:: pycon >>> from manim import XKCD >>> XKCD.AVOCADO ManimColor('#90B134') Or, alternatively: .. code:: pycon >>> from manim.utils.color.XKCD import AVOCADO >>> AVOCADO ManimColor('#90B134') The following modules contain the predefined color constants: .. autosummary:: :toctree: ../reference manim_colors AS2700 BS381 DVIPSNAMES SVGNAMES XKCD X11 """ from __future__ import annotations from . import AS2700, BS381, DVIPSNAMES, SVGNAMES, X11, XKCD from .core import * from .manim_colors import * _all_color_dict: dict[str, ManimColor] = { k: v for k, v in globals().items() if isinstance(v, ManimColor) } ================================================ FILE: manim/utils/color/AS2700.py ================================================ """Australian Color Standard In 1985 the Australian Independent Color Standard AS 2700 was created. In this standard, all colors can be identified via a category code (one of B -- Blue, G -- Green, N -- Neutrals (grey), P -- Purple, R -- Red, T -- Blue/Green, X -- Yellow/Red, Y -- Yellow) and a number. The colors also have (natural) names. To use the colors from this list, access them directly from the module (which is exposed to Manim's global name space):
|
Green, N -- Neutrals (grey), P -- Purple, R -- Red, T -- Blue/Green, X -- Yellow/Red, Y -- Yellow) and a number. The colors also have (natural) names. To use the colors from this list, access them directly from the module (which is exposed to Manim's global name space): .. code:: pycon >>> from manim import AS2700 >>> AS2700.B23_BRIGHT_BLUE ManimColor('#174F90') List of Color Constants ----------------------- These hex values (taken from https://www.w3schools.com/colors/colors_australia.asp) are non official approximate values intended to simulate AS 2700 colors: .. automanimcolormodule:: manim.utils.color.AS2700 """ from __future__ import annotations from .core import ManimColor B11_RICH_BLUE = ManimColor("#2B3770") B12_ROYAL_BLUE = ManimColor("#2C3563") B13_NAVY_BLUE = ManimColor("#28304D") B14_SAPHHIRE = ManimColor("#28426B") B15_MID_BLUE = ManimColor("#144B6F") B21_ULTRAMARINE = ManimColor("#2C5098") B22_HOMEBUSH_BLUE = ManimColor("#215097") B23_BRIGHT_BLUE = ManimColor("#174F90") B24_HARBOUR_BLUE = ManimColor("#1C6293") B25_AQUA = ManimColor("#5097AC") B32_POWDER_BLUE = ManimColor("#B7C8DB") B33_MIST_BLUE = ManimColor("#E0E6E2") B34_PARADISE_BLUE = ManimColor("#3499BA") B35_PALE_BLUE = ManimColor("#CDE4E2") B41_BLUEBELL = ManimColor("#5B94D1") B42_PURPLE_BLUE = ManimColor("#5E7899") B43_GREY_BLUE = ManimColor("#627C8D") B44_LIGHT_GREY_BLUE = ManimColor("#C0C0C1") B45_SKY_BLUE = ManimColor("#7DB7C7") B51_PERIWINKLE = ManimColor("#3871AC") B53_DARK_GREY_BLUE = ManimColor("#4F6572") B55_STORM_BLUE = ManimColor("#3F7C94") B61_CORAL_SEA = ManimColor("#2B3873") B62_MIDNIGHT_BLUE = ManimColor("#292A34") B64_CHARCOAL = ManimColor("#363E45") G11_BOTTLE_GREEN = ManimColor("#253A32") G12_HOLLY = ManimColor("#21432D") G13_EMERALD = ManimColor("#195F35") G14_MOSS_GREEN = ManimColor("#33572D") G15_RAINFOREST_GREEN = ManimColor("#3D492D") G16_TRAFFIC_GREEN = ManimColor("#305442") G17_MINT_GREEN = ManimColor("#006B45") G21_JADE = ManimColor("#127453") G22_SERPENTINE = ManimColor("#78A681") G23_SHAMROCK = ManimColor("#336634") G24_FERN_TREE = ManimColor("#477036") G25_OLIVE = ManimColor("#595B2A") G26_APPLE_GREEN = ManimColor("#4E9843") G27_HOMEBUSH_GREEN = ManimColor("#017F4D") G31_VERTIGRIS = ManimColor("#468A65") G32_OPALINE = ManimColor("#AFCBB8") G33_LETTUCE = ManimColor("#7B9954") G34_AVOCADO = ManimColor("#757C4C") G35_LIME_GREEN = ManimColor("#89922E") G36_KIKUYU = ManimColor("#95B43B") G37_BEANSTALK = ManimColor("#45A56A") G41_LAWN_GREEN = ManimColor("#0D875D") G42_GLACIER = ManimColor("#D5E1D2") G43_SURF_GREEN = ManimColor("#C8C8A7") G44_PALM_GREEN = ManimColor("#99B179") G45_CHARTREUSE = ManimColor("#C7C98D") G46_CITRONELLA = ManimColor("#BFC83E") G47_CRYSTAL_GREEN = ManimColor("#ADCCA8") G51_SPRUCE = ManimColor("#05674F") G52_EUCALYPTUS = ManimColor("#66755B") G53_BANKSIA = ManimColor("#929479") G54_MIST_GREEN = ManimColor("#7A836D") G55_LICHEN = ManimColor("#A7A98C") G56_SAGE_GREEN = ManimColor("#677249") G61_DARK_GREEN = ManimColor("#283533") G62_RIVERGUM = ManimColor("#617061") G63_DEEP_BRONZE_GREEN = ManimColor("#333334") G64_SLATE = ManimColor("#5E6153") G65_TI_TREE = ManimColor("#5D5F4E") G66_ENVIRONMENT_GREEN = ManimColor("#484C3F") G67_ZUCCHINI = ManimColor("#2E443A") N11_PEARL_GREY = ManimColor("#D8D3C7") N12_PASTEL_GREY = ManimColor("#CCCCCC") N14_WHITE = ManimColor("#FFFFFF") N15_HOMEBUSH_GREY = ManimColor("#A29B93") N22_CLOUD_GREY = ManimColor("#C4C1B9") N23_NEUTRAL_GREY = ManimColor("#CCCCCC") N24_SILVER_GREY = ManimColor("#BDC7C5") N25_BIRCH_GREY = ManimColor("#ABA498") N32_GREEN_GREY = ManimColor("#8E9282") N33_LIGHTBOX_GREY = ManimColor("#ACADAD") N35_LIGHT_GREY = ManimColor("#A6A7A1") N41_OYSTER = ManimColor("#998F78") N42_STORM_GREY = ManimColor("#858F88") N43_PIPELINE_GREY = ManimColor("#999999") N44_BRIDGE_GREY = ManimColor("#767779") N45_KOALA_GREY = ManimColor("#928F88") N52_MID_GREY = ManimColor("#727A77") N53_BLUE_GREY = ManimColor("#7C8588") N54_BASALT = ManimColor("#585C63") N55_LEAD_GREY = ManimColor("#5E5C58") N61_BLACK = ManimColor("#2A2A2C") N63_PEWTER = ManimColor("#596064") N64_DARK_GREY = ManimColor("#4B5259") N65_GRAPHITE_GREY = ManimColor("#45474A") P11_MAGENTA = ManimColor("#7B2B48") P12_PURPLE = ManimColor("#85467B") P13_VIOLET = ManimColor("#5D3A61") P14_BLUEBERRY = ManimColor("#4C4176") P21_SUNSET_PINK = ManimColor("#E3BBBD") P22_CYCLAMEN = ManimColor("#83597D") P23_LILAC = ManimColor("#A69FB1") P24_JACKARANDA = ManimColor("#795F91") P31_DUSTY_PINK = ManimColor("#DBBEBC") P33_RIBBON_PINK = ManimColor("#D1BCC9") P41_ERICA_PINK = ManimColor("#C55A83") P42_MULBERRY = ManimColor("#A06574") P43_WISTERIA = ManimColor("#756D91") P52_PLUM = ManimColor("#6E3D4B") R11_INTERNATIONAL_ORANGE = ManimColor("#CE482A") R12_SCARLET = ManimColor("#CD392A") R13_SIGNAL_RED = ManimColor("#BA312B") R14_WARATAH = ManimColor("#AA2429") R15_CRIMSON = ManimColor("#9E2429") R21_TANGERINE = ManimColor("#E96957") R22_HOMEBUSH_RED = ManimColor("#D83A2D") R23_LOLLIPOP = ManimColor("#CC5058") R24_STRAWBERRY = ManimColor("#B4292A") R25_ROSE_PINK = ManimColor("#E8919C") R32_APPLE_BLOSSOM = ManimColor("#F2E1D8") R33_GHOST_GUM = ManimColor("#E8DAD4") R34_MUSHROOM = ManimColor("#D7C0B6") R35_DEEP_ROSE = ManimColor("#CD6D71") R41_SHELL_PINK = ManimColor("#F9D9BB") R42_SALMON_PINK = ManimColor("#D99679") R43_RED_DUST = ManimColor("#D0674F") R44_POSSUM = ManimColor("#A18881") R45_RUBY = ManimColor("#8F3E5C") R51_BURNT_PINK = ManimColor("#E19B8E") R52_TERRACOTTA = ManimColor("#A04C36") R53_RED_GUM = ManimColor("#8D4338") R54_RASPBERRY = ManimColor("#852F31") R55_CLARET = ManimColor("#67292D") R62_VENETIAN_RED = ManimColor("#77372B") R63_RED_OXIDE = ManimColor("#663334") R64_DEEP_INDIAN_RED = ManimColor("#542E2B") R65_MAROON = ManimColor("#3F2B3C") T11_TROPICAL_BLUE = ManimColor("#006698") T12_DIAMANTIA = ManimColor("#006C74") T14_MALACHITE = ManimColor("#105154")
|
= ManimColor("#F9D9BB") R42_SALMON_PINK = ManimColor("#D99679") R43_RED_DUST = ManimColor("#D0674F") R44_POSSUM = ManimColor("#A18881") R45_RUBY = ManimColor("#8F3E5C") R51_BURNT_PINK = ManimColor("#E19B8E") R52_TERRACOTTA = ManimColor("#A04C36") R53_RED_GUM = ManimColor("#8D4338") R54_RASPBERRY = ManimColor("#852F31") R55_CLARET = ManimColor("#67292D") R62_VENETIAN_RED = ManimColor("#77372B") R63_RED_OXIDE = ManimColor("#663334") R64_DEEP_INDIAN_RED = ManimColor("#542E2B") R65_MAROON = ManimColor("#3F2B3C") T11_TROPICAL_BLUE = ManimColor("#006698") T12_DIAMANTIA = ManimColor("#006C74") T14_MALACHITE = ManimColor("#105154") T15_TURQUOISE = ManimColor("#098587") T22_ORIENTAL_BLUE = ManimColor("#358792") T24_BLUE_JADE = ManimColor("#427F7E") T32_HUON_GREEN = ManimColor("#72B3B1") T33_SMOKE_BLUE = ManimColor("#9EB6B2") T35_GREEN_ICE = ManimColor("#78AEA2") T44_BLUE_GUM = ManimColor("#6A8A88") T45_COOTAMUNDRA = ManimColor("#759E91") T51_MOUNTAIN_BLUE = ManimColor("#295668") T53_PEACOCK_BLUE = ManimColor("#245764") T63_TEAL = ManimColor("#183F4E") X11_BUTTERSCOTCH = ManimColor("#D38F43") X12_PUMPKIN = ManimColor("#DD7E1A") X13_MARIGOLD = ManimColor("#ED7F15") X14_MANDARIN = ManimColor("#E45427") X15_ORANGE = ManimColor("#E36C2B") X21_PALE_OCHRE = ManimColor("#DAA45F") X22_SAFFRON = ManimColor("#F6AA51") X23_APRICOT = ManimColor("#FEB56D") X24_ROCKMELON = ManimColor("#F6894B") X31_RAFFIA = ManimColor("#EBC695") X32_MAGNOLIA = ManimColor("#F1DEBE") X33_WARM_WHITE = ManimColor("#F3E7D4") X34_DRIFTWOOD = ManimColor("#D5C4AE") X41_BUFF = ManimColor("#C28A44") X42_BISCUIT = ManimColor("#DEBA92") X43_BEIGE = ManimColor("#C9AA8C") X45_CINNAMON = ManimColor("#AC826D") X51_TAN = ManimColor("#8F5F32") X52_COFFEE = ManimColor("#AD7948") X53_GOLDEN_TAN = ManimColor("#925629") X54_BROWN = ManimColor("#68452C") X55_NUT_BROWN = ManimColor("#764832") X61_WOMBAT = ManimColor("#6E5D52") X62_DARK_EARTH = ManimColor("#6E5D52") X63_IRONBARK = ManimColor("#443B36") X64_CHOCOLATE = ManimColor("#4A3B31") X65_DARK_BROWN = ManimColor("#4F372D") Y11_CANARY = ManimColor("#E7BD11") Y12_WATTLE = ManimColor("#E8AF01") Y13_VIVID_YELLOW = ManimColor("#FCAE01") Y14_GOLDEN_YELLOW = ManimColor("#F5A601") Y15_SUNFLOWER = ManimColor("#FFA709") Y16_INCA_GOLD = ManimColor("#DF8C19") Y21_PRIMROSE = ManimColor("#F5CF5B") Y22_CUSTARD = ManimColor("#EFD25C") Y23_BUTTERCUP = ManimColor("#E0CD41") Y24_STRAW = ManimColor("#E3C882") Y25_DEEP_CREAM = ManimColor("#F3C968") Y26_HOMEBUSH_GOLD = ManimColor("#FCC51A") Y31_LILY_GREEN = ManimColor("#E3E3CD") Y32_FLUMMERY = ManimColor("#E6DF9E") Y33_PALE_PRIMROSE = ManimColor("#F5F3CE") Y34_CREAM = ManimColor("#EFE3BE") Y35_OFF_WHITE = ManimColor("#F1E9D5") Y41_OLIVE_YELLOW = ManimColor("#8E7426") Y42_MUSTARD = ManimColor("#C4A32E") Y43_PARCHMENT = ManimColor("#D4C9A3") Y44_SAND = ManimColor("#DCC18B") Y45_MANILLA = ManimColor("#E5D0A7") Y51_BRONZE_OLIVE = ManimColor("#695D3E") Y52_CHAMOIS = ManimColor("#BEA873") Y53_SANDSTONE = ManimColor("#D5BF8E") Y54_OATMEAL = ManimColor("#CAAE82") Y55_DEEP_STONE = ManimColor("#BC9969") Y56_MERINO = ManimColor("#C9B79E") Y61_BLACK_OLIVE = ManimColor("#47473B") Y62_SUGAR_CANE = ManimColor("#BCA55C") Y63_KHAKI = ManimColor("#826843") Y65_MUSHROOM = ManimColor("#A39281") Y66_MUDSTONE = ManimColor("#574E45") ================================================ FILE: manim/utils/color/BS381.py ================================================ """British Color Standard This module contains colors defined in one of the British Standards for colors, BS381C. This standard specifies colors used in identification, coding, and other special purposes. See https://www.britishstandardcolour.com/ for more information. To use the colors from this list, access them directly from the module (which is exposed to Manim's global name space): .. code:: pycon >>> from manim import BS381 >>> BS381.OXFORD_BLUE ManimColor('#1F3057') List of Color Constants ----------------------- These hex values (taken from https://www.w3schools.com/colors/colors_british.asp) are non official approximate values intended to simulate the ones defined in the standard: .. automanimcolormodule:: manim.utils.color.BS381 """ from __future__ import annotations from .core import ManimColor BS381_101 = ManimColor("#94BFAC") SKY_BLUE = ManimColor("#94BFAC") BS381_102 = ManimColor("#5B9291") TURQUOISE_BLUE = ManimColor("#5B9291") BS381_103 = ManimColor("#3B6879") PEACOCK_BLUE = ManimColor("#3B6879") BS381_104 = ManimColor("#264D7E") AZURE_BLUE = ManimColor("#264D7E") BS381_105 = ManimColor("#1F3057") OXFORD_BLUE = ManimColor("#1F3057") BS381_106 = ManimColor("#2A283D") ROYAL_BLUE = ManimColor("#2A283D") BS381_107 = ManimColor("#3A73A9") STRONG_BLUE = ManimColor("#3A73A9") BS381_108 = ManimColor("#173679") AIRCRAFT_BLUE = ManimColor("#173679") BS381_109 = ManimColor("#1C5680") MIDDLE_BLUE = ManimColor("#1C5680") BS381_110 = ManimColor("#2C3E75") ROUNDEL_BLUE = ManimColor("#2C3E75") BS381_111 = ManimColor("#8CC5BB") PALE_BLUE = ManimColor("#8CC5BB") BS381_112 = ManimColor("#78ADC2") ARCTIC_BLUE = ManimColor("#78ADC2") FIESTA_BLUE = ManimColor("#78ADC2") BS381_113 = ManimColor("#3F687D") DEEP_SAXE_BLUE = ManimColor("#3F687D") BS381_114 = ManimColor("#1F4B61") RAIL_BLUE = ManimColor("#1F4B61") BS381_115 = ManimColor("#5F88C1") COBALT_BLUE = ManimColor("#5F88C1") BS381_166 = ManimColor("#2458AF") FRENCH_BLUE = ManimColor("#2458AF") BS381_169 = ManimColor("#135B75") TRAFFIC_BLUE = ManimColor("#135B75") BS381_172 = ManimColor("#A7C6EB") PALE_ROUNDEL_BLUE = ManimColor("#A7C6EB") BS381_174 = ManimColor("#64A0AA") ORIENT_BLUE = ManimColor("#64A0AA") BS381_175 = ManimColor("#4F81C5") LIGHT_FRENCH_BLUE = ManimColor("#4F81C5") BS381_210 = ManimColor("#BBC9A5") SKY = ManimColor("#BBC9A5") BS381_216
|
ManimColor("#3F687D") BS381_114 = ManimColor("#1F4B61") RAIL_BLUE = ManimColor("#1F4B61") BS381_115 = ManimColor("#5F88C1") COBALT_BLUE = ManimColor("#5F88C1") BS381_166 = ManimColor("#2458AF") FRENCH_BLUE = ManimColor("#2458AF") BS381_169 = ManimColor("#135B75") TRAFFIC_BLUE = ManimColor("#135B75") BS381_172 = ManimColor("#A7C6EB") PALE_ROUNDEL_BLUE = ManimColor("#A7C6EB") BS381_174 = ManimColor("#64A0AA") ORIENT_BLUE = ManimColor("#64A0AA") BS381_175 = ManimColor("#4F81C5") LIGHT_FRENCH_BLUE = ManimColor("#4F81C5") BS381_210 = ManimColor("#BBC9A5") SKY = ManimColor("#BBC9A5") BS381_216 = ManimColor("#BCD890") EAU_DE_NIL = ManimColor("#BCD890") BS381_217 = ManimColor("#96BF65") SEA_GREEN = ManimColor("#96BF65") BS381_218 = ManimColor("#698B47") GRASS_GREEN = ManimColor("#698B47") BS381_219 = ManimColor("#757639") SAGE_GREEN = ManimColor("#757639") BS381_220 = ManimColor("#4B5729") OLIVE_GREEN = ManimColor("#4B5729") BS381_221 = ManimColor("#507D3A") BRILLIANT_GREEN = ManimColor("#507D3A") BS381_222 = ManimColor("#6A7031") LIGHT_BRONZE_GREEN = ManimColor("#6A7031") BS381_223 = ManimColor("#49523A") MIDDLE_BRONZE_GREEN = ManimColor("#49523A") BS381_224 = ManimColor("#3E4630") DEEP_BRONZE_GREEN = ManimColor("#3E4630") BS381_225 = ManimColor("#406A28") LIGHT_BRUNSWICK_GREEN = ManimColor("#406A28") BS381_226 = ManimColor("#33533B") MID_BRUNSWICK_GREEN = ManimColor("#33533B") BS381_227 = ManimColor("#254432") DEEP_BRUNSWICK_GREEN = ManimColor("#254432") BS381_228 = ManimColor("#428B64") EMERALD_GREEN = ManimColor("#428B64") BS381_241 = ManimColor("#4F5241") DARK_GREEN = ManimColor("#4F5241") BS381_262 = ManimColor("#44945E") BOLD_GREEN = ManimColor("#44945E") BS381_267 = ManimColor("#476A4C") DEEP_CHROME_GREEN = ManimColor("#476A4C") TRAFFIC_GREEN = ManimColor("#476A4C") BS381_275 = ManimColor("#8FC693") OPALINE_GREEN = ManimColor("#8FC693") BS381_276 = ManimColor("#2E4C1E") LINCON_GREEN = ManimColor("#2E4C1E") BS381_277 = ManimColor("#364A20") CYPRESS_GREEN = ManimColor("#364A20") BS381_278 = ManimColor("#87965A") LIGHT_OLIVE_GREEN = ManimColor("#87965A") BS381_279 = ManimColor("#3B3629") STEEL_FURNITURE_GREEN = ManimColor("#3B3629") BS381_280 = ManimColor("#68AB77") VERDIGRIS_GREEN = ManimColor("#68AB77") BS381_282 = ManimColor("#506B52") FOREST_GREEN = ManimColor("#506B52") BS381_283 = ManimColor("#7E8F6E") AIRCRAFT_GREY_GREEN = ManimColor("#7E8F6E") BS381_284 = ManimColor("#6B6F5A") SPRUCE_GREEN = ManimColor("#6B6F5A") BS381_285 = ManimColor("#5F5C4B") NATO_GREEN = ManimColor("#5F5C4B") BS381_298 = ManimColor("#4F5138") OLIVE_DRAB = ManimColor("#4F5138") BS381_309 = ManimColor("#FEEC04") CANARY_YELLOW = ManimColor("#FEEC04") BS381_310 = ManimColor("#FEF963") PRIMROSE = ManimColor("#FEF963") BS381_315 = ManimColor("#FEF96A") GRAPEFRUIT = ManimColor("#FEF96A") BS381_320 = ManimColor("#9E7339") LIGHT_BROWN = ManimColor("#9E7339") BS381_337 = ManimColor("#4C4A3C") VERY_DARK_DRAB = ManimColor("#4C4A3C") BS381_350 = ManimColor("#7B6B4F") DARK_EARTH = ManimColor("#7B6B4F") BS381_352 = ManimColor("#FCED96") PALE_CREAM = ManimColor("#FCED96") BS381_353 = ManimColor("#FDF07A") DEEP_CREAM = ManimColor("#FDF07A") BS381_354 = ManimColor("#E9BB43") PRIMROSE_2 = ManimColor("#E9BB43") BS381_355 = ManimColor("#FDD906") LEMON = ManimColor("#FDD906") BS381_356 = ManimColor("#FCC808") GOLDEN_YELLOW = ManimColor("#FCC808") BS381_358 = ManimColor("#F6C870") LIGHT_BUFF = ManimColor("#F6C870") BS381_359 = ManimColor("#DBAC50") MIDDLE_BUFF = ManimColor("#DBAC50") BS381_361 = ManimColor("#D4B97D") LIGHT_STONE = ManimColor("#D4B97D") BS381_362 = ManimColor("#AC7C42") MIDDLE_STONE = ManimColor("#AC7C42") BS381_363 = ManimColor("#FDE706") BOLD_YELLOW = ManimColor("#FDE706") BS381_364 = ManimColor("#CEC093") PORTLAND_STONE = ManimColor("#CEC093") BS381_365 = ManimColor("#F4F0BD") VELLUM = ManimColor("#F4F0BD") BS381_366 = ManimColor("#F5E7A1") LIGHT_BEIGE = ManimColor("#F5E7A1") BS381_367 = ManimColor("#FEF6BF") MANILLA = ManimColor("#fef6bf") BS381_368 = ManimColor("#DD7B00") TRAFFIC_YELLOW = ManimColor("#DD7B00") BS381_369 = ManimColor("#FEEBA8") BISCUIT = ManimColor("#feeba8") BS381_380 = ManimColor("#BBA38A") CAMOUFLAGE_DESERT_SAND = ManimColor("#BBA38A") BS381_384 = ManimColor("#EEDFA5") LIGHT_STRAW = ManimColor("#EEDFA5") BS381_385 = ManimColor("#E8C88F") LIGHT_BISCUIT = ManimColor("#E8C88F") BS381_386 = ManimColor("#E6C18D") CHAMPAGNE = ManimColor("#e6c18d") BS381_387 = ManimColor("#CFB48A") SUNRISE = ManimColor("#cfb48a") SUNSHINE = ManimColor("#cfb48a") BS381_388 = ManimColor("#E4CF93") BEIGE = ManimColor("#e4cf93") BS381_389 = ManimColor("#B2A788") CAMOUFLAGE_BEIGE = ManimColor("#B2A788") BS381_397 = ManimColor("#F3D163") JASMINE_YELLOW = ManimColor("#F3D163") BS381_411 = ManimColor("#74542F") MIDDLE_BROWN = ManimColor("#74542F") BS381_412 = ManimColor("#5C422E") DARK_BROWN = ManimColor("#5C422E") BS381_413 = ManimColor("#402D21") NUT_BROWN = ManimColor("#402D21") BS381_414 = ManimColor("#A86C29") GOLDEN_BROWN = ManimColor("#A86C29") BS381_415 = ManimColor("#61361E") IMPERIAL_BROWN = ManimColor("#61361E") BS381_420 = ManimColor("#A89177") DARK_CAMOUFLAGE_DESERT_SAND = ManimColor("#A89177") BS381_435 = ManimColor("#845B4D") CAMOUFLAGE_RED = ManimColor("#845B4D") BS381_436 = ManimColor("#564B47") DARK_CAMOUFLAGE_BROWN = ManimColor("#564B47") BS381_439 = ManimColor("#753B1E") ORANGE_BROWN = ManimColor("#753B1E") BS381_443 = ManimColor("#C98A71") SALMON = ManimColor("#c98a71") BS381_444 = ManimColor("#A65341") TERRACOTTA = ManimColor("#a65341") BS381_445 = ManimColor("#83422B") VENETIAN_RED = ManimColor("#83422B") BS381_446 = ManimColor("#774430") RED_OXIDE = ManimColor("#774430") BS381_447 = ManimColor("#F3B28B") SALMON_PINK = ManimColor("#F3B28B") BS381_448 = ManimColor("#67403A") DEEP_INDIAN_RED = ManimColor("#67403A") BS381_449 = ManimColor("#693B3F") LIGHT_PURPLE_BROWN = ManimColor("#693B3F") BS381_452 = ManimColor("#613339") DARK_CRIMSON = ManimColor("#613339") BS381_453
|
ManimColor("#753B1E") BS381_443 = ManimColor("#C98A71") SALMON = ManimColor("#c98a71") BS381_444 = ManimColor("#A65341") TERRACOTTA = ManimColor("#a65341") BS381_445 = ManimColor("#83422B") VENETIAN_RED = ManimColor("#83422B") BS381_446 = ManimColor("#774430") RED_OXIDE = ManimColor("#774430") BS381_447 = ManimColor("#F3B28B") SALMON_PINK = ManimColor("#F3B28B") BS381_448 = ManimColor("#67403A") DEEP_INDIAN_RED = ManimColor("#67403A") BS381_449 = ManimColor("#693B3F") LIGHT_PURPLE_BROWN = ManimColor("#693B3F") BS381_452 = ManimColor("#613339") DARK_CRIMSON = ManimColor("#613339") BS381_453 = ManimColor("#FBDED6") SHELL_PINK = ManimColor("#FBDED6") BS381_454 = ManimColor("#E8A1A2") PALE_ROUNDEL_RED = ManimColor("#E8A1A2") BS381_460 = ManimColor("#BD8F56") DEEP_BUFF = ManimColor("#BD8F56") BS381_473 = ManimColor("#793932") GULF_RED = ManimColor("#793932") BS381_489 = ManimColor("#8D5B41") LEAF_BROWN = ManimColor("#8D5B41") BS381_490 = ManimColor("#573320") BEECH_BROWN = ManimColor("#573320") BS381_499 = ManimColor("#59493E") SERVICE_BROWN = ManimColor("#59493E") BS381_536 = ManimColor("#BB3016") POPPY = ManimColor("#bb3016") BS381_537 = ManimColor("#DD3420") SIGNAL_RED = ManimColor("#DD3420") BS381_538 = ManimColor("#C41C22") POST_OFFICE_RED = ManimColor("#C41C22") CHERRY = ManimColor("#c41c22") BS381_539 = ManimColor("#D21E2B") CURRANT_RED = ManimColor("#D21E2B") BS381_540 = ManimColor("#8B1A32") CRIMSON = ManimColor("#8b1a32") BS381_541 = ManimColor("#471B21") MAROON = ManimColor("#471b21") BS381_542 = ManimColor("#982D57") RUBY = ManimColor("#982d57") BS381_557 = ManimColor("#EF841E") LIGHT_ORANGE = ManimColor("#EF841E") BS381_564 = ManimColor("#DD3524") BOLD_RED = ManimColor("#DD3524") BS381_568 = ManimColor("#FB9C06") APRICOT = ManimColor("#fb9c06") BS381_570 = ManimColor("#A83C19") TRAFFIC_RED = ManimColor("#A83C19") BS381_591 = ManimColor("#D04E09") DEEP_ORANGE = ManimColor("#D04E09") BS381_592 = ManimColor("#E45523") INTERNATIONAL_ORANGE = ManimColor("#E45523") BS381_593 = ManimColor("#F24816") RAIL_RED = ManimColor("#F24816") AZO_ORANGE = ManimColor("#F24816") BS381_626 = ManimColor("#A0A9AA") CAMOUFLAGE_GREY = ManimColor("#A0A9AA") BS381_627 = ManimColor("#BEC0B8") LIGHT_AIRCRAFT_GREY = ManimColor("#BEC0B8") BS381_628 = ManimColor("#9D9D7E") SILVER_GREY = ManimColor("#9D9D7E") BS381_629 = ManimColor("#7A838B") DARK_CAMOUFLAGE_GREY = ManimColor("#7A838B") BS381_630 = ManimColor("#A5AD98") FRENCH_GREY = ManimColor("#A5AD98") BS381_631 = ManimColor("#9AAA9F") LIGHT_GREY = ManimColor("#9AAA9F") BS381_632 = ManimColor("#6B7477") DARK_ADMIRALTY_GREY = ManimColor("#6B7477") BS381_633 = ManimColor("#424C53") RAF_BLUE_GREY = ManimColor("#424C53") BS381_634 = ManimColor("#6F7264") SLATE = ManimColor("#6f7264") BS381_635 = ManimColor("#525B55") LEAD = ManimColor("#525b55") BS381_636 = ManimColor("#5F7682") PRU_BLUE = ManimColor("#5F7682") BS381_637 = ManimColor("#8E9B9C") MEDIUM_SEA_GREY = ManimColor("#8E9B9C") BS381_638 = ManimColor("#6C7377") DARK_SEA_GREY = ManimColor("#6C7377") BS381_639 = ManimColor("#667563") LIGHT_SLATE_GREY = ManimColor("#667563") BS381_640 = ManimColor("#566164") EXTRA_DARK_SEA_GREY = ManimColor("#566164") BS381_642 = ManimColor("#282B2F") NIGHT = ManimColor("#282b2f") BS381_671 = ManimColor("#4E5355") MIDDLE_GRAPHITE = ManimColor("#4E5355") BS381_676 = ManimColor("#A9B7B9") LIGHT_WEATHERWORK_GREY = ManimColor("#A9B7B9") BS381_677 = ManimColor("#676F76") DARK_WEATHERWORK_GREY = ManimColor("#676F76") BS381_692 = ManimColor("#7B93A3") SMOKE_GREY = ManimColor("#7B93A3") BS381_693 = ManimColor("#88918D") AIRCRAFT_GREY = ManimColor("#88918D") BS381_694 = ManimColor("#909A92") DOVE_GREY = ManimColor("#909A92") BS381_697 = ManimColor("#B6D3CC") LIGHT_ADMIRALTY_GREY = ManimColor("#B6D3CC") BS381_796 = ManimColor("#6E4A75") DARK_VIOLET = ManimColor("#6E4A75") BS381_797 = ManimColor("#C9A8CE") LIGHT_VIOLET = ManimColor("#C9A8CE") ================================================ FILE: manim/utils/color/DVIPSNAMES.py ================================================ r"""dvips Colors This module contains the colors defined in the dvips driver, which are commonly accessed as named colors in LaTeX via the ``\usepackage[dvipsnames]{xcolor}`` package. To use the colors from this list, access them directly from the module (which is exposed to Manim's global name space): .. code:: pycon >>> from manim import DVIPSNAMES >>> DVIPSNAMES.DARKORCHID ManimColor('#A4538A') List of Color Constants ----------------------- These hex values are derived from those specified in the ``xcolor`` package documentation (see https://ctan.org/pkg/xcolor): .. automanimcolormodule:: manim.utils.color.DVIPSNAMES """ from __future__ import annotations from .core import ManimColor AQUAMARINE = ManimColor("#00B5BE") BITTERSWEET = ManimColor("#C04F17") APRICOT = ManimColor("#FBB982") BLACK = ManimColor("#221E1F") BLUE = ManimColor("#2D2F92") BLUEGREEN = ManimColor("#00B3B8") BLUEVIOLET = ManimColor("#473992") BRICKRED = ManimColor("#B6321C") BROWN = ManimColor("#792500") BURNTORANGE = ManimColor("#F7921D") CADETBLUE = ManimColor("#74729A") CARNATIONPINK = ManimColor("#F282B4") CERULEAN = ManimColor("#00A2E3") CORNFLOWERBLUE = ManimColor("#41B0E4") CYAN = ManimColor("#00AEEF") DANDELION = ManimColor("#FDBC42") DARKORCHID = ManimColor("#A4538A") EMERALD = ManimColor("#00A99D") FORESTGREEN = ManimColor("#009B55") FUCHSIA = ManimColor("#8C368C") GOLDENROD = ManimColor("#FFDF42") GRAY = ManimColor("#949698") GREEN = ManimColor("#00A64F") GREENYELLOW = ManimColor("#DFE674") JUNGLEGREEN = ManimColor("#00A99A") LAVENDER
|
ManimColor("#792500") BURNTORANGE = ManimColor("#F7921D") CADETBLUE = ManimColor("#74729A") CARNATIONPINK = ManimColor("#F282B4") CERULEAN = ManimColor("#00A2E3") CORNFLOWERBLUE = ManimColor("#41B0E4") CYAN = ManimColor("#00AEEF") DANDELION = ManimColor("#FDBC42") DARKORCHID = ManimColor("#A4538A") EMERALD = ManimColor("#00A99D") FORESTGREEN = ManimColor("#009B55") FUCHSIA = ManimColor("#8C368C") GOLDENROD = ManimColor("#FFDF42") GRAY = ManimColor("#949698") GREEN = ManimColor("#00A64F") GREENYELLOW = ManimColor("#DFE674") JUNGLEGREEN = ManimColor("#00A99A") LAVENDER = ManimColor("#F49EC4") LIMEGREEN = ManimColor("#8DC73E") MAGENTA = ManimColor("#EC008C") MAHOGANY = ManimColor("#A9341F") MAROON = ManimColor("#AF3235") MELON = ManimColor("#F89E7B") MIDNIGHTBLUE = ManimColor("#006795") MULBERRY = ManimColor("#A93C93") NAVYBLUE = ManimColor("#006EB8") OLIVEGREEN = ManimColor("#3C8031") ORANGE = ManimColor("#F58137") ORANGERED = ManimColor("#ED135A") ORCHID = ManimColor("#AF72B0") PEACH = ManimColor("#F7965A") PERIWINKLE = ManimColor("#7977B8") PINEGREEN = ManimColor("#008B72") PLUM = ManimColor("#92268F") PROCESSBLUE = ManimColor("#00B0F0") PURPLE = ManimColor("#99479B") RAWSIENNA = ManimColor("#974006") RED = ManimColor("#ED1B23") REDORANGE = ManimColor("#F26035") REDVIOLET = ManimColor("#A1246B") RHODAMINE = ManimColor("#EF559F") ROYALBLUE = ManimColor("#0071BC") ROYALPURPLE = ManimColor("#613F99") RUBINERED = ManimColor("#ED017D") SALMON = ManimColor("#F69289") SEAGREEN = ManimColor("#3FBC9D") SEPIA = ManimColor("#671800") SKYBLUE = ManimColor("#46C5DD") SPRINGGREEN = ManimColor("#C6DC67") TAN = ManimColor("#DA9D76") TEALBLUE = ManimColor("#00AEB3") THISTLE = ManimColor("#D883B7") TURQUOISE = ManimColor("#00B4CE") VIOLET = ManimColor("#58429B") VIOLETRED = ManimColor("#EF58A0") WHITE = ManimColor("#FFFFFF") WILDSTRAWBERRY = ManimColor("#EE2967") YELLOW = ManimColor("#FFF200") YELLOWGREEN = ManimColor("#98CC70") YELLOWORANGE = ManimColor("#FAA21A") ================================================ FILE: manim/utils/color/manim_colors.py ================================================ """Colors included in the global name space. These colors form Manim's default color space. .. manim:: ColorsOverview :save_last_frame: :hide_source: import manim.utils.color.manim_colors as Colors class ColorsOverview(Scene): def construct(self): def color_group(color): group = VGroup( *[ Line(ORIGIN, RIGHT * 1.5, stroke_width=35, color=getattr(Colors, name.upper())) for name in subnames(color) ] ).arrange_submobjects(buff=0.4, direction=DOWN) name = Text(color).scale(0.6).next_to(group, UP, buff=0.3) if any(decender in color for decender in "gjpqy"): name.shift(DOWN * 0.08) group.add(name) return group def subnames(name): return [name + "_" + char for char in "abcde"] color_groups = VGroup( *[ color_group(color) for color in [ "blue", "teal", "green", "yellow", "gold", "red", "maroon", "purple", ] ] ).arrange_submobjects(buff=0.2, aligned_edge=DOWN) for line, char in zip(color_groups[0], "abcde"): color_groups.add(Text(char).scale(0.6).next_to(line, LEFT, buff=0.2)) def named_lines_group(length, color_names, labels, align_to_block): colors = [getattr(Colors, color.upper()) for color in color_names] lines = VGroup( *[ Line( ORIGIN, RIGHT * length, stroke_width=55, color=color, ) for color in colors ] ).arrange_submobjects(buff=0.6, direction=DOWN) for line, name, color in zip(lines, labels, colors): line.add(Text(name, color=color.contrasting()).scale(0.6).move_to(line)) lines.next_to(color_groups, DOWN, buff=0.5).align_to( color_groups[align_to_block], LEFT ) return lines other_colors = ( "pink", "light_pink", "orange", "light_brown", "dark_brown", "gray_brown", ) other_lines = named_lines_group( 3.2, other_colors, other_colors, 0, ) gray_lines = named_lines_group( 6.6, ["white"] + subnames("gray") + ["black"], [ "white", "lighter_gray / gray_a", "light_gray / gray_b", "gray / gray_c", "dark_gray / gray_d", "darker_gray / gray_e", "black", ], 2, ) pure_colors = ( "pure_red", "pure_green", "pure_blue", ) pure_lines = named_lines_group( 3.2, pure_colors, pure_colors, 6, ) self.add(color_groups, other_lines, gray_lines, pure_lines) VGroup(*self.mobjects).move_to(ORIGIN) .. automanimcolormodule:: manim.utils.color.manim_colors """ from __future__ import annotations from .core import ManimColor WHITE = ManimColor("#FFFFFF") GRAY_A = ManimColor("#DDDDDD") GREY_A = ManimColor("#DDDDDD") GRAY_B = ManimColor("#BBBBBB") GREY_B = ManimColor("#BBBBBB") GRAY_C = ManimColor("#888888") GREY_C = ManimColor("#888888") GRAY_D = ManimColor("#444444") GREY_D = ManimColor("#444444") GRAY_E = ManimColor("#222222") GREY_E = ManimColor("#222222") BLACK = ManimColor("#000000") LIGHTER_GRAY = ManimColor("#DDDDDD") LIGHTER_GREY = ManimColor("#DDDDDD") LIGHT_GRAY = ManimColor("#BBBBBB") LIGHT_GREY = ManimColor("#BBBBBB") GRAY = ManimColor("#888888") GREY = ManimColor("#888888") DARK_GRAY = ManimColor("#444444") DARK_GREY = ManimColor("#444444") DARKER_GRAY = ManimColor("#222222") DARKER_GREY = ManimColor("#222222") BLUE_A = ManimColor("#C7E9F1") BLUE_B = ManimColor("#9CDCEB") BLUE_C = ManimColor("#58C4DD") BLUE_D = ManimColor("#29ABCA") BLUE_E =
|
GREY_E = ManimColor("#222222") BLACK = ManimColor("#000000") LIGHTER_GRAY = ManimColor("#DDDDDD") LIGHTER_GREY = ManimColor("#DDDDDD") LIGHT_GRAY = ManimColor("#BBBBBB") LIGHT_GREY = ManimColor("#BBBBBB") GRAY = ManimColor("#888888") GREY = ManimColor("#888888") DARK_GRAY = ManimColor("#444444") DARK_GREY = ManimColor("#444444") DARKER_GRAY = ManimColor("#222222") DARKER_GREY = ManimColor("#222222") BLUE_A = ManimColor("#C7E9F1") BLUE_B = ManimColor("#9CDCEB") BLUE_C = ManimColor("#58C4DD") BLUE_D = ManimColor("#29ABCA") BLUE_E = ManimColor("#236B8E") PURE_BLUE = ManimColor("#0000FF") BLUE = ManimColor("#58C4DD") DARK_BLUE = ManimColor("#236B8E") TEAL_A = ManimColor("#ACEAD7") TEAL_B = ManimColor("#76DDC0") TEAL_C = ManimColor("#5CD0B3") TEAL_D = ManimColor("#55C1A7") TEAL_E = ManimColor("#49A88F") TEAL = ManimColor("#5CD0B3") GREEN_A = ManimColor("#C9E2AE") GREEN_B = ManimColor("#A6CF8C") GREEN_C = ManimColor("#83C167") GREEN_D = ManimColor("#77B05D") GREEN_E = ManimColor("#699C52") PURE_GREEN = ManimColor("#00FF00") GREEN = ManimColor("#83C167") YELLOW_A = ManimColor("#FFF1B6") YELLOW_B = ManimColor("#FFEA94") YELLOW_C = ManimColor("#FFFF00") YELLOW_D = ManimColor("#F4D345") YELLOW_E = ManimColor("#E8C11C") YELLOW = ManimColor("#FFFF00") GOLD_A = ManimColor("#F7C797") GOLD_B = ManimColor("#F9B775") GOLD_C = ManimColor("#F0AC5F") GOLD_D = ManimColor("#E1A158") GOLD_E = ManimColor("#C78D46") GOLD = ManimColor("#F0AC5F") RED_A = ManimColor("#F7A1A3") RED_B = ManimColor("#FF8080") RED_C = ManimColor("#FC6255") RED_D = ManimColor("#E65A4C") RED_E = ManimColor("#CF5044") PURE_RED = ManimColor("#FF0000") RED = ManimColor("#FC6255") MAROON_A = ManimColor("#ECABC1") MAROON_B = ManimColor("#EC92AB") MAROON_C = ManimColor("#C55F73") MAROON_D = ManimColor("#A24D61") MAROON_E = ManimColor("#94424F") MAROON = ManimColor("#C55F73") PURPLE_A = ManimColor("#CAA3E8") PURPLE_B = ManimColor("#B189C6") PURPLE_C = ManimColor("#9A72AC") PURPLE_D = ManimColor("#715582") PURPLE_E = ManimColor("#644172") PURPLE = ManimColor("#9A72AC") PINK = ManimColor("#D147BD") LIGHT_PINK = ManimColor("#DC75CD") ORANGE = ManimColor("#FF862F") LIGHT_BROWN = ManimColor("#CD853F") DARK_BROWN = ManimColor("#8B4513") GRAY_BROWN = ManimColor("#736357") GREY_BROWN = ManimColor("#736357") # Colors used for Manim Community's logo and banner LOGO_WHITE = ManimColor("#ECE7E2") LOGO_GREEN = ManimColor("#87C2A5") LOGO_BLUE = ManimColor("#525893") LOGO_RED = ManimColor("#E07A5F") LOGO_BLACK = ManimColor("#343434") _all_manim_colors: list[ManimColor] = [ x for x in globals().values() if isinstance(x, ManimColor) ] ================================================ FILE: manim/utils/color/SVGNAMES.py ================================================ r"""SVG 1.1 Colors This module contains the colors defined in the SVG 1.1 specification, which are commonly accessed as named colors in LaTeX via the ``\usepackage[svgnames]{xcolor}`` package. To use the colors from this list, access them directly from the module (which is exposed to Manim's global name space): .. code:: pycon >>> from manim import SVGNAMES >>> SVGNAMES.LIGHTCORAL ManimColor('#EF7F7F') List of Color Constants ----------------------- These hex values are derived from those specified in the ``xcolor`` package documentation (see https://ctan.org/pkg/xcolor): .. automanimcolormodule:: manim.utils.color.SVGNAMES """ from __future__ import annotations from .core import ManimColor ALICEBLUE = ManimColor("#EFF7FF") ANTIQUEWHITE = ManimColor("#F9EAD7") AQUA = ManimColor("#00FFFF") AQUAMARINE = ManimColor("#7EFFD3") AZURE = ManimColor("#EFFFFF") BEIGE = ManimColor("#F4F4DC") BISQUE = ManimColor("#FFE3C4") BLACK = ManimColor("#000000") BLANCHEDALMOND = ManimColor("#FFEACD") BLUE = ManimColor("#0000FF") BLUEVIOLET = ManimColor("#892BE2") BROWN = ManimColor("#A52A2A") BURLYWOOD = ManimColor("#DDB787") CADETBLUE = ManimColor("#5E9EA0") CHARTREUSE = ManimColor("#7EFF00") CHOCOLATE = ManimColor("#D2681D") CORAL = ManimColor("#FF7E4F") CORNFLOWERBLUE = ManimColor("#6395ED") CORNSILK = ManimColor("#FFF7DC") CRIMSON = ManimColor("#DC143B") CYAN = ManimColor("#00FFFF") DARKBLUE = ManimColor("#00008A") DARKCYAN = ManimColor("#008A8A") DARKGOLDENROD = ManimColor("#B7850B") DARKGRAY = ManimColor("#A9A9A9") DARKGREEN = ManimColor("#006300") DARKGREY = ManimColor("#A9A9A9") DARKKHAKI = ManimColor("#BCB66B") DARKMAGENTA = ManimColor("#8A008A") DARKOLIVEGREEN = ManimColor("#546B2F") DARKORANGE = ManimColor("#FF8C00") DARKORCHID = ManimColor("#9931CC") DARKRED = ManimColor("#8A0000") DARKSALMON = ManimColor("#E8967A") DARKSEAGREEN = ManimColor("#8EBB8E") DARKSLATEBLUE = ManimColor("#483D8A") DARKSLATEGRAY = ManimColor("#2F4F4F") DARKSLATEGREY = ManimColor("#2F4F4F") DARKTURQUOISE = ManimColor("#00CED1") DARKVIOLET = ManimColor("#9300D3") DEEPPINK = ManimColor("#FF1492") DEEPSKYBLUE = ManimColor("#00BFFF") DIMGRAY = ManimColor("#686868") DIMGREY = ManimColor("#686868") DODGERBLUE = ManimColor("#1D90FF") FIREBRICK = ManimColor("#B12121") FLORALWHITE = ManimColor("#FFF9EF") FORESTGREEN = ManimColor("#218A21") FUCHSIA = ManimColor("#FF00FF") GAINSBORO = ManimColor("#DCDCDC") GHOSTWHITE = ManimColor("#F7F7FF") GOLD =
|
DARKSLATEBLUE = ManimColor("#483D8A") DARKSLATEGRAY = ManimColor("#2F4F4F") DARKSLATEGREY = ManimColor("#2F4F4F") DARKTURQUOISE = ManimColor("#00CED1") DARKVIOLET = ManimColor("#9300D3") DEEPPINK = ManimColor("#FF1492") DEEPSKYBLUE = ManimColor("#00BFFF") DIMGRAY = ManimColor("#686868") DIMGREY = ManimColor("#686868") DODGERBLUE = ManimColor("#1D90FF") FIREBRICK = ManimColor("#B12121") FLORALWHITE = ManimColor("#FFF9EF") FORESTGREEN = ManimColor("#218A21") FUCHSIA = ManimColor("#FF00FF") GAINSBORO = ManimColor("#DCDCDC") GHOSTWHITE = ManimColor("#F7F7FF") GOLD = ManimColor("#FFD700") GOLDENROD = ManimColor("#DAA51F") GRAY = ManimColor("#7F7F7F") GREEN = ManimColor("#007F00") GREENYELLOW = ManimColor("#ADFF2F") GREY = ManimColor("#7F7F7F") HONEYDEW = ManimColor("#EFFFEF") HOTPINK = ManimColor("#FF68B3") INDIANRED = ManimColor("#CD5B5B") INDIGO = ManimColor("#4A0082") IVORY = ManimColor("#FFFFEF") KHAKI = ManimColor("#EFE58C") LAVENDER = ManimColor("#E5E5F9") LAVENDERBLUSH = ManimColor("#FFEFF4") LAWNGREEN = ManimColor("#7CFC00") LEMONCHIFFON = ManimColor("#FFF9CD") LIGHTBLUE = ManimColor("#ADD8E5") LIGHTCORAL = ManimColor("#EF7F7F") LIGHTCYAN = ManimColor("#E0FFFF") LIGHTGOLDENROD = ManimColor("#EDDD82") LIGHTGOLDENRODYELLOW = ManimColor("#F9F9D2") LIGHTGRAY = ManimColor("#D3D3D3") LIGHTGREEN = ManimColor("#90ED90") LIGHTGREY = ManimColor("#D3D3D3") LIGHTPINK = ManimColor("#FFB5C0") LIGHTSALMON = ManimColor("#FFA07A") LIGHTSEAGREEN = ManimColor("#1FB1AA") LIGHTSKYBLUE = ManimColor("#87CEF9") LIGHTSLATEBLUE = ManimColor("#8470FF") LIGHTSLATEGRAY = ManimColor("#778799") LIGHTSLATEGREY = ManimColor("#778799") LIGHTSTEELBLUE = ManimColor("#AFC4DD") LIGHTYELLOW = ManimColor("#FFFFE0") LIME = ManimColor("#00FF00") LIMEGREEN = ManimColor("#31CD31") LINEN = ManimColor("#F9EFE5") MAGENTA = ManimColor("#FF00FF") MAROON = ManimColor("#7F0000") MEDIUMAQUAMARINE = ManimColor("#66CDAA") MEDIUMBLUE = ManimColor("#0000CD") MEDIUMORCHID = ManimColor("#BA54D3") MEDIUMPURPLE = ManimColor("#9270DB") MEDIUMSEAGREEN = ManimColor("#3BB271") MEDIUMSLATEBLUE = ManimColor("#7B68ED") MEDIUMSPRINGGREEN = ManimColor("#00F99A") MEDIUMTURQUOISE = ManimColor("#48D1CC") MEDIUMVIOLETRED = ManimColor("#C61584") MIDNIGHTBLUE = ManimColor("#181870") MINTCREAM = ManimColor("#F4FFF9") MISTYROSE = ManimColor("#FFE3E1") MOCCASIN = ManimColor("#FFE3B5") NAVAJOWHITE = ManimColor("#FFDDAD") NAVY = ManimColor("#00007F") NAVYBLUE = ManimColor("#00007F") OLDLACE = ManimColor("#FCF4E5") OLIVE = ManimColor("#7F7F00") OLIVEDRAB = ManimColor("#6B8D22") ORANGE = ManimColor("#FFA500") ORANGERED = ManimColor("#FF4400") ORCHID = ManimColor("#DA70D6") PALEGOLDENROD = ManimColor("#EDE8AA") PALEGREEN = ManimColor("#97FB97") PALETURQUOISE = ManimColor("#AFEDED") PALEVIOLETRED = ManimColor("#DB7092") PAPAYAWHIP = ManimColor("#FFEED4") PEACHPUFF = ManimColor("#FFDAB8") PERU = ManimColor("#CD843F") PINK = ManimColor("#FFBFCA") PLUM = ManimColor("#DDA0DD") POWDERBLUE = ManimColor("#AFE0E5") PURPLE = ManimColor("#7F007F") RED = ManimColor("#FF0000") ROSYBROWN = ManimColor("#BB8E8E") ROYALBLUE = ManimColor("#4168E1") SADDLEBROWN = ManimColor("#8A4413") SALMON = ManimColor("#F97F72") SANDYBROWN = ManimColor("#F3A45F") SEAGREEN = ManimColor("#2D8A56") SEASHELL = ManimColor("#FFF4ED") SIENNA = ManimColor("#A0512C") SILVER = ManimColor("#BFBFBF") SKYBLUE = ManimColor("#87CEEA") SLATEBLUE = ManimColor("#6959CD") SLATEGRAY = ManimColor("#707F90") SLATEGREY = ManimColor("#707F90") SNOW = ManimColor("#FFF9F9") SPRINGGREEN = ManimColor("#00FF7E") STEELBLUE = ManimColor("#4682B3") TAN = ManimColor("#D2B38C") TEAL = ManimColor("#007F7F") THISTLE = ManimColor("#D8BFD8") TOMATO = ManimColor("#FF6347") TURQUOISE = ManimColor("#3FE0CF") VIOLET = ManimColor("#ED82ED") VIOLETRED = ManimColor("#D01F90") WHEAT = ManimColor("#F4DDB2") WHITE = ManimColor("#FFFFFF") WHITESMOKE = ManimColor("#F4F4F4") YELLOW = ManimColor("#FFFF00") YELLOWGREEN = ManimColor("#9ACD30") ================================================ FILE: manim/utils/color/X11.py ================================================ # from https://www.w3schools.com/colors/colors_x11.asp """X11 Colors These color and their names (taken from https://www.w3schools.com/colors/colors_x11.asp) were developed at the Massachusetts Intitute of Technology (MIT) during the development of color based computer display system. To use the colors from this list, access them directly from the module (which is exposed to Manim's global name space): .. code:: pycon >>> from manim import X11 >>> X11.BEIGE ManimColor('#F5F5DC') List of Color Constants ----------------------- .. automanimcolormodule:: manim.utils.color.X11 """ from __future__ import annotations from .core import ManimColor ALICEBLUE = ManimColor("#F0F8FF") ANTIQUEWHITE = ManimColor("#FAEBD7") ANTIQUEWHITE1 = ManimColor("#FFEFDB") ANTIQUEWHITE2 = ManimColor("#EEDFCC") ANTIQUEWHITE3 = ManimColor("#CDC0B0") ANTIQUEWHITE4 = ManimColor("#8B8378") AQUAMARINE1 = ManimColor("#7FFFD4") AQUAMARINE2 = ManimColor("#76EEC6") AQUAMARINE4 = ManimColor("#458B74") AZURE1 = ManimColor("#F0FFFF") AZURE2 = ManimColor("#E0EEEE") AZURE3 = ManimColor("#C1CDCD") AZURE4 = ManimColor("#838B8B") BEIGE = ManimColor("#F5F5DC") BISQUE1 = ManimColor("#FFE4C4") BISQUE2 = ManimColor("#EED5B7") BISQUE3 = ManimColor("#CDB79E") BISQUE4 = ManimColor("#8B7D6B") BLACK = ManimColor("#000000") BLANCHEDALMOND = ManimColor("#FFEBCD") BLUE1 = ManimColor("#0000FF") BLUE2 = ManimColor("#0000EE") BLUE4 =
|
AQUAMARINE1 = ManimColor("#7FFFD4") AQUAMARINE2 = ManimColor("#76EEC6") AQUAMARINE4 = ManimColor("#458B74") AZURE1 = ManimColor("#F0FFFF") AZURE2 = ManimColor("#E0EEEE") AZURE3 = ManimColor("#C1CDCD") AZURE4 = ManimColor("#838B8B") BEIGE = ManimColor("#F5F5DC") BISQUE1 = ManimColor("#FFE4C4") BISQUE2 = ManimColor("#EED5B7") BISQUE3 = ManimColor("#CDB79E") BISQUE4 = ManimColor("#8B7D6B") BLACK = ManimColor("#000000") BLANCHEDALMOND = ManimColor("#FFEBCD") BLUE1 = ManimColor("#0000FF") BLUE2 = ManimColor("#0000EE") BLUE4 = ManimColor("#00008B") BLUEVIOLET = ManimColor("#8A2BE2") BROWN = ManimColor("#A52A2A") BROWN1 = ManimColor("#FF4040") BROWN2 = ManimColor("#EE3B3B") BROWN3 = ManimColor("#CD3333") BROWN4 = ManimColor("#8B2323") BURLYWOOD = ManimColor("#DEB887") BURLYWOOD1 = ManimColor("#FFD39B") BURLYWOOD2 = ManimColor("#EEC591") BURLYWOOD3 = ManimColor("#CDAA7D") BURLYWOOD4 = ManimColor("#8B7355") CADETBLUE = ManimColor("#5F9EA0") CADETBLUE1 = ManimColor("#98F5FF") CADETBLUE2 = ManimColor("#8EE5EE") CADETBLUE3 = ManimColor("#7AC5CD") CADETBLUE4 = ManimColor("#53868B") CHARTREUSE1 = ManimColor("#7FFF00") CHARTREUSE2 = ManimColor("#76EE00") CHARTREUSE3 = ManimColor("#66CD00") CHARTREUSE4 = ManimColor("#458B00") CHOCOLATE = ManimColor("#D2691E") CHOCOLATE1 = ManimColor("#FF7F24") CHOCOLATE2 = ManimColor("#EE7621") CHOCOLATE3 = ManimColor("#CD661D") CORAL = ManimColor("#FF7F50") CORAL1 = ManimColor("#FF7256") CORAL2 = ManimColor("#EE6A50") CORAL3 = ManimColor("#CD5B45") CORAL4 = ManimColor("#8B3E2F") CORNFLOWERBLUE = ManimColor("#6495ED") CORNSILK1 = ManimColor("#FFF8DC") CORNSILK2 = ManimColor("#EEE8CD") CORNSILK3 = ManimColor("#CDC8B1") CORNSILK4 = ManimColor("#8B8878") CYAN1 = ManimColor("#00FFFF") CYAN2 = ManimColor("#00EEEE") CYAN3 = ManimColor("#00CDCD") CYAN4 = ManimColor("#008B8B") DARKGOLDENROD = ManimColor("#B8860B") DARKGOLDENROD1 = ManimColor("#FFB90F") DARKGOLDENROD2 = ManimColor("#EEAD0E") DARKGOLDENROD3 = ManimColor("#CD950C") DARKGOLDENROD4 = ManimColor("#8B6508") DARKGREEN = ManimColor("#006400") DARKKHAKI = ManimColor("#BDB76B") DARKOLIVEGREEN = ManimColor("#556B2F") DARKOLIVEGREEN1 = ManimColor("#CAFF70") DARKOLIVEGREEN2 = ManimColor("#BCEE68") DARKOLIVEGREEN3 = ManimColor("#A2CD5A") DARKOLIVEGREEN4 = ManimColor("#6E8B3D") DARKORANGE = ManimColor("#FF8C00") DARKORANGE1 = ManimColor("#FF7F00") DARKORANGE2 = ManimColor("#EE7600") DARKORANGE3 = ManimColor("#CD6600") DARKORANGE4 = ManimColor("#8B4500") DARKORCHID = ManimColor("#9932CC") DARKORCHID1 = ManimColor("#BF3EFF") DARKORCHID2 = ManimColor("#B23AEE") DARKORCHID3 = ManimColor("#9A32CD") DARKORCHID4 = ManimColor("#68228B") DARKSALMON = ManimColor("#E9967A") DARKSEAGREEN = ManimColor("#8FBC8F") DARKSEAGREEN1 = ManimColor("#C1FFC1") DARKSEAGREEN2 = ManimColor("#B4EEB4") DARKSEAGREEN3 = ManimColor("#9BCD9B") DARKSEAGREEN4 = ManimColor("#698B69") DARKSLATEBLUE = ManimColor("#483D8B") DARKSLATEGRAY = ManimColor("#2F4F4F") DARKSLATEGRAY1 = ManimColor("#97FFFF") DARKSLATEGRAY2 = ManimColor("#8DEEEE") DARKSLATEGRAY3 = ManimColor("#79CDCD") DARKSLATEGRAY4 = ManimColor("#528B8B") DARKTURQUOISE = ManimColor("#00CED1") DARKVIOLET = ManimColor("#9400D3") DEEPPINK1 = ManimColor("#FF1493") DEEPPINK2 = ManimColor("#EE1289") DEEPPINK3 = ManimColor("#CD1076") DEEPPINK4 = ManimColor("#8B0A50") DEEPSKYBLUE1 = ManimColor("#00BFFF") DEEPSKYBLUE2 = ManimColor("#00B2EE") DEEPSKYBLUE3 = ManimColor("#009ACD") DEEPSKYBLUE4 = ManimColor("#00688B") DIMGRAY = ManimColor("#696969") DODGERBLUE1 = ManimColor("#1E90FF") DODGERBLUE2 = ManimColor("#1C86EE") DODGERBLUE3 = ManimColor("#1874CD") DODGERBLUE4 = ManimColor("#104E8B") FIREBRICK = ManimColor("#B22222") FIREBRICK1 = ManimColor("#FF3030") FIREBRICK2 = ManimColor("#EE2C2C") FIREBRICK3 = ManimColor("#CD2626") FIREBRICK4 = ManimColor("#8B1A1A") FLORALWHITE = ManimColor("#FFFAF0") FORESTGREEN = ManimColor("#228B22") GAINSBORO = ManimColor("#DCDCDC") GHOSTWHITE = ManimColor("#F8F8FF") GOLD1 = ManimColor("#FFD700") GOLD2 = ManimColor("#EEC900") GOLD3 = ManimColor("#CDAD00") GOLD4 = ManimColor("#8B7500") GOLDENROD = ManimColor("#DAA520") GOLDENROD1 = ManimColor("#FFC125") GOLDENROD2 = ManimColor("#EEB422") GOLDENROD3 = ManimColor("#CD9B1D") GOLDENROD4 = ManimColor("#8B6914") GRAY = ManimColor("#BEBEBE") GRAY1 = ManimColor("#030303") GRAY2 = ManimColor("#050505") GRAY3 = ManimColor("#080808") GRAY4 = ManimColor("#0A0A0A") GRAY5 = ManimColor("#0D0D0D") GRAY6 = ManimColor("#0F0F0F") GRAY7 = ManimColor("#121212") GRAY8 = ManimColor("#141414") GRAY9 = ManimColor("#171717") GRAY10 = ManimColor("#1A1A1A") GRAY11 = ManimColor("#1C1C1C") GRAY12 = ManimColor("#1F1F1F") GRAY13 = ManimColor("#212121") GRAY14 = ManimColor("#242424") GRAY15 = ManimColor("#262626") GRAY16 = ManimColor("#292929") GRAY17 = ManimColor("#2B2B2B") GRAY18 = ManimColor("#2E2E2E") GRAY19 = ManimColor("#303030") GRAY20 = ManimColor("#333333") GRAY21 = ManimColor("#363636") GRAY22 = ManimColor("#383838") GRAY23 = ManimColor("#3B3B3B") GRAY24 = ManimColor("#3D3D3D") GRAY25 = ManimColor("#404040") GRAY26 = ManimColor("#424242") GRAY27 = ManimColor("#454545") GRAY28 = ManimColor("#474747") GRAY29 = ManimColor("#4A4A4A") GRAY30 = ManimColor("#4D4D4D") GRAY31 = ManimColor("#4F4F4F") GRAY32 = ManimColor("#525252") GRAY33 = ManimColor("#545454") GRAY34 = ManimColor("#575757") GRAY35 = ManimColor("#595959") GRAY36 = ManimColor("#5C5C5C") GRAY37 = ManimColor("#5E5E5E") GRAY38 = ManimColor("#616161") GRAY39 = ManimColor("#636363") GRAY40 = ManimColor("#666666") GRAY41 = ManimColor("#696969") GRAY42 = ManimColor("#6B6B6B") GRAY43 = ManimColor("#6E6E6E") GRAY44 =
|
GRAY28 = ManimColor("#474747") GRAY29 = ManimColor("#4A4A4A") GRAY30 = ManimColor("#4D4D4D") GRAY31 = ManimColor("#4F4F4F") GRAY32 = ManimColor("#525252") GRAY33 = ManimColor("#545454") GRAY34 = ManimColor("#575757") GRAY35 = ManimColor("#595959") GRAY36 = ManimColor("#5C5C5C") GRAY37 = ManimColor("#5E5E5E") GRAY38 = ManimColor("#616161") GRAY39 = ManimColor("#636363") GRAY40 = ManimColor("#666666") GRAY41 = ManimColor("#696969") GRAY42 = ManimColor("#6B6B6B") GRAY43 = ManimColor("#6E6E6E") GRAY44 = ManimColor("#707070") GRAY45 = ManimColor("#737373") GRAY46 = ManimColor("#757575") GRAY47 = ManimColor("#787878") GRAY48 = ManimColor("#7A7A7A") GRAY49 = ManimColor("#7D7D7D") GRAY50 = ManimColor("#7F7F7F") GRAY51 = ManimColor("#828282") GRAY52 = ManimColor("#858585") GRAY53 = ManimColor("#878787") GRAY54 = ManimColor("#8A8A8A") GRAY55 = ManimColor("#8C8C8C") GRAY56 = ManimColor("#8F8F8F") GRAY57 = ManimColor("#919191") GRAY58 = ManimColor("#949494") GRAY59 = ManimColor("#969696") GRAY60 = ManimColor("#999999") GRAY61 = ManimColor("#9C9C9C") GRAY62 = ManimColor("#9E9E9E") GRAY63 = ManimColor("#A1A1A1") GRAY64 = ManimColor("#A3A3A3") GRAY65 = ManimColor("#A6A6A6") GRAY66 = ManimColor("#A8A8A8") GRAY67 = ManimColor("#ABABAB") GRAY68 = ManimColor("#ADADAD") GRAY69 = ManimColor("#B0B0B0") GRAY70 = ManimColor("#B3B3B3") GRAY71 = ManimColor("#B5B5B5") GRAY72 = ManimColor("#B8B8B8") GRAY73 = ManimColor("#BABABA") GRAY74 = ManimColor("#BDBDBD") GRAY75 = ManimColor("#BFBFBF") GRAY76 = ManimColor("#C2C2C2") GRAY77 = ManimColor("#C4C4C4") GRAY78 = ManimColor("#C7C7C7") GRAY79 = ManimColor("#C9C9C9") GRAY80 = ManimColor("#CCCCCC") GRAY81 = ManimColor("#CFCFCF") GRAY82 = ManimColor("#D1D1D1") GRAY83 = ManimColor("#D4D4D4") GRAY84 = ManimColor("#D6D6D6") GRAY85 = ManimColor("#D9D9D9") GRAY86 = ManimColor("#DBDBDB") GRAY87 = ManimColor("#DEDEDE") GRAY88 = ManimColor("#E0E0E0") GRAY89 = ManimColor("#E3E3E3") GRAY90 = ManimColor("#E5E5E5") GRAY91 = ManimColor("#E8E8E8") GRAY92 = ManimColor("#EBEBEB") GRAY93 = ManimColor("#EDEDED") GRAY94 = ManimColor("#F0F0F0") GRAY95 = ManimColor("#F2F2F2") GRAY97 = ManimColor("#F7F7F7") GRAY98 = ManimColor("#FAFAFA") GRAY99 = ManimColor("#FCFCFC") GREEN1 = ManimColor("#00FF00") GREEN2 = ManimColor("#00EE00") GREEN3 = ManimColor("#00CD00") GREEN4 = ManimColor("#008B00") GREENYELLOW = ManimColor("#ADFF2F") HONEYDEW1 = ManimColor("#F0FFF0") HONEYDEW2 = ManimColor("#E0EEE0") HONEYDEW3 = ManimColor("#C1CDC1") HONEYDEW4 = ManimColor("#838B83") HOTPINK = ManimColor("#FF69B4") HOTPINK1 = ManimColor("#FF6EB4") HOTPINK2 = ManimColor("#EE6AA7") HOTPINK3 = ManimColor("#CD6090") HOTPINK4 = ManimColor("#8B3A62") INDIANRED = ManimColor("#CD5C5C") INDIANRED1 = ManimColor("#FF6A6A") INDIANRED2 = ManimColor("#EE6363") INDIANRED3 = ManimColor("#CD5555") INDIANRED4 = ManimColor("#8B3A3A") IVORY1 = ManimColor("#FFFFF0") IVORY2 = ManimColor("#EEEEE0") IVORY3 = ManimColor("#CDCDC1") IVORY4 = ManimColor("#8B8B83") KHAKI = ManimColor("#F0E68C") KHAKI1 = ManimColor("#FFF68F") KHAKI2 = ManimColor("#EEE685") KHAKI3 = ManimColor("#CDC673") KHAKI4 = ManimColor("#8B864E") LAVENDER = ManimColor("#E6E6FA") LAVENDERBLUSH1 = ManimColor("#FFF0F5") LAVENDERBLUSH2 = ManimColor("#EEE0E5") LAVENDERBLUSH3 = ManimColor("#CDC1C5") LAVENDERBLUSH4 = ManimColor("#8B8386") LAWNGREEN = ManimColor("#7CFC00") LEMONCHIFFON1 = ManimColor("#FFFACD") LEMONCHIFFON2 = ManimColor("#EEE9BF") LEMONCHIFFON3 = ManimColor("#CDC9A5") LEMONCHIFFON4 = ManimColor("#8B8970") LIGHT = ManimColor("#EEDD82") LIGHTBLUE = ManimColor("#ADD8E6") LIGHTBLUE1 = ManimColor("#BFEFFF") LIGHTBLUE2 = ManimColor("#B2DFEE") LIGHTBLUE3 = ManimColor("#9AC0CD") LIGHTBLUE4 = ManimColor("#68838B") LIGHTCORAL = ManimColor("#F08080") LIGHTCYAN1 = ManimColor("#E0FFFF") LIGHTCYAN2 = ManimColor("#D1EEEE") LIGHTCYAN3 = ManimColor("#B4CDCD") LIGHTCYAN4 = ManimColor("#7A8B8B") LIGHTGOLDENROD1 = ManimColor("#FFEC8B") LIGHTGOLDENROD2 = ManimColor("#EEDC82") LIGHTGOLDENROD3 = ManimColor("#CDBE70") LIGHTGOLDENROD4 = ManimColor("#8B814C") LIGHTGOLDENRODYELLOW = ManimColor("#FAFAD2") LIGHTGRAY = ManimColor("#D3D3D3") LIGHTPINK = ManimColor("#FFB6C1") LIGHTPINK1 = ManimColor("#FFAEB9") LIGHTPINK2 = ManimColor("#EEA2AD") LIGHTPINK3 = ManimColor("#CD8C95") LIGHTPINK4 = ManimColor("#8B5F65") LIGHTSALMON1 = ManimColor("#FFA07A") LIGHTSALMON2 = ManimColor("#EE9572") LIGHTSALMON3 = ManimColor("#CD8162") LIGHTSALMON4 = ManimColor("#8B5742") LIGHTSEAGREEN = ManimColor("#20B2AA") LIGHTSKYBLUE = ManimColor("#87CEFA") LIGHTSKYBLUE1 = ManimColor("#B0E2FF") LIGHTSKYBLUE2 = ManimColor("#A4D3EE") LIGHTSKYBLUE3 = ManimColor("#8DB6CD") LIGHTSKYBLUE4 = ManimColor("#607B8B") LIGHTSLATEBLUE = ManimColor("#8470FF") LIGHTSLATEGRAY = ManimColor("#778899") LIGHTSTEELBLUE = ManimColor("#B0C4DE") LIGHTSTEELBLUE1 = ManimColor("#CAE1FF") LIGHTSTEELBLUE2 = ManimColor("#BCD2EE") LIGHTSTEELBLUE3 = ManimColor("#A2B5CD") LIGHTSTEELBLUE4 = ManimColor("#6E7B8B") LIGHTYELLOW1 = ManimColor("#FFFFE0") LIGHTYELLOW2 = ManimColor("#EEEED1") LIGHTYELLOW3 = ManimColor("#CDCDB4") LIGHTYELLOW4 = ManimColor("#8B8B7A") LIMEGREEN = ManimColor("#32CD32") LINEN = ManimColor("#FAF0E6") MAGENTA = ManimColor("#FF00FF") MAGENTA2 = ManimColor("#EE00EE") MAGENTA3 = ManimColor("#CD00CD") MAGENTA4 = ManimColor("#8B008B") MAROON = ManimColor("#B03060") MAROON1 = ManimColor("#FF34B3") MAROON2 = ManimColor("#EE30A7") MAROON3 = ManimColor("#CD2990") MAROON4 = ManimColor("#8B1C62") MEDIUM = ManimColor("#66CDAA") MEDIUMAQUAMARINE = ManimColor("#66CDAA") MEDIUMBLUE = ManimColor("#0000CD") MEDIUMORCHID =
|
LIGHTYELLOW3 = ManimColor("#CDCDB4") LIGHTYELLOW4 = ManimColor("#8B8B7A") LIMEGREEN = ManimColor("#32CD32") LINEN = ManimColor("#FAF0E6") MAGENTA = ManimColor("#FF00FF") MAGENTA2 = ManimColor("#EE00EE") MAGENTA3 = ManimColor("#CD00CD") MAGENTA4 = ManimColor("#8B008B") MAROON = ManimColor("#B03060") MAROON1 = ManimColor("#FF34B3") MAROON2 = ManimColor("#EE30A7") MAROON3 = ManimColor("#CD2990") MAROON4 = ManimColor("#8B1C62") MEDIUM = ManimColor("#66CDAA") MEDIUMAQUAMARINE = ManimColor("#66CDAA") MEDIUMBLUE = ManimColor("#0000CD") MEDIUMORCHID = ManimColor("#BA55D3") MEDIUMORCHID1 = ManimColor("#E066FF") MEDIUMORCHID2 = ManimColor("#D15FEE") MEDIUMORCHID3 = ManimColor("#B452CD") MEDIUMORCHID4 = ManimColor("#7A378B") MEDIUMPURPLE = ManimColor("#9370DB") MEDIUMPURPLE1 = ManimColor("#AB82FF") MEDIUMPURPLE2 = ManimColor("#9F79EE") MEDIUMPURPLE3 = ManimColor("#8968CD") MEDIUMPURPLE4 = ManimColor("#5D478B") MEDIUMSEAGREEN = ManimColor("#3CB371") MEDIUMSLATEBLUE = ManimColor("#7B68EE") MEDIUMSPRINGGREEN = ManimColor("#00FA9A") MEDIUMTURQUOISE = ManimColor("#48D1CC") MEDIUMVIOLETRED = ManimColor("#C71585") MIDNIGHTBLUE = ManimColor("#191970") MINTCREAM = ManimColor("#F5FFFA") MISTYROSE1 = ManimColor("#FFE4E1") MISTYROSE2 = ManimColor("#EED5D2") MISTYROSE3 = ManimColor("#CDB7B5") MISTYROSE4 = ManimColor("#8B7D7B") MOCCASIN = ManimColor("#FFE4B5") NAVAJOWHITE1 = ManimColor("#FFDEAD") NAVAJOWHITE2 = ManimColor("#EECFA1") NAVAJOWHITE3 = ManimColor("#CDB38B") NAVAJOWHITE4 = ManimColor("#8B795E") NAVYBLUE = ManimColor("#000080") OLDLACE = ManimColor("#FDF5E6") OLIVEDRAB = ManimColor("#6B8E23") OLIVEDRAB1 = ManimColor("#C0FF3E") OLIVEDRAB2 = ManimColor("#B3EE3A") OLIVEDRAB4 = ManimColor("#698B22") ORANGE1 = ManimColor("#FFA500") ORANGE2 = ManimColor("#EE9A00") ORANGE3 = ManimColor("#CD8500") ORANGE4 = ManimColor("#8B5A00") ORANGERED1 = ManimColor("#FF4500") ORANGERED2 = ManimColor("#EE4000") ORANGERED3 = ManimColor("#CD3700") ORANGERED4 = ManimColor("#8B2500") ORCHID = ManimColor("#DA70D6") ORCHID1 = ManimColor("#FF83FA") ORCHID2 = ManimColor("#EE7AE9") ORCHID3 = ManimColor("#CD69C9") ORCHID4 = ManimColor("#8B4789") PALE = ManimColor("#DB7093") PALEGOLDENROD = ManimColor("#EEE8AA") PALEGREEN = ManimColor("#98FB98") PALEGREEN1 = ManimColor("#9AFF9A") PALEGREEN2 = ManimColor("#90EE90") PALEGREEN3 = ManimColor("#7CCD7C") PALEGREEN4 = ManimColor("#548B54") PALETURQUOISE = ManimColor("#AFEEEE") PALETURQUOISE1 = ManimColor("#BBFFFF") PALETURQUOISE2 = ManimColor("#AEEEEE") PALETURQUOISE3 = ManimColor("#96CDCD") PALETURQUOISE4 = ManimColor("#668B8B") PALEVIOLETRED = ManimColor("#DB7093") PALEVIOLETRED1 = ManimColor("#FF82AB") PALEVIOLETRED2 = ManimColor("#EE799F") PALEVIOLETRED3 = ManimColor("#CD6889") PALEVIOLETRED4 = ManimColor("#8B475D") PAPAYAWHIP = ManimColor("#FFEFD5") PEACHPUFF1 = ManimColor("#FFDAB9") PEACHPUFF2 = ManimColor("#EECBAD") PEACHPUFF3 = ManimColor("#CDAF95") PEACHPUFF4 = ManimColor("#8B7765") PINK = ManimColor("#FFC0CB") PINK1 = ManimColor("#FFB5C5") PINK2 = ManimColor("#EEA9B8") PINK3 = ManimColor("#CD919E") PINK4 = ManimColor("#8B636C") PLUM = ManimColor("#DDA0DD") PLUM1 = ManimColor("#FFBBFF") PLUM2 = ManimColor("#EEAEEE") PLUM3 = ManimColor("#CD96CD") PLUM4 = ManimColor("#8B668B") POWDERBLUE = ManimColor("#B0E0E6") PURPLE = ManimColor("#A020F0") PURPLE1 = ManimColor("#9B30FF") PURPLE2 = ManimColor("#912CEE") PURPLE3 = ManimColor("#7D26CD") PURPLE4 = ManimColor("#551A8B") RED1 = ManimColor("#FF0000") RED2 = ManimColor("#EE0000") RED3 = ManimColor("#CD0000") RED4 = ManimColor("#8B0000") ROSYBROWN = ManimColor("#BC8F8F") ROSYBROWN1 = ManimColor("#FFC1C1") ROSYBROWN2 = ManimColor("#EEB4B4") ROSYBROWN3 = ManimColor("#CD9B9B") ROSYBROWN4 = ManimColor("#8B6969") ROYALBLUE = ManimColor("#4169E1") ROYALBLUE1 = ManimColor("#4876FF") ROYALBLUE2 = ManimColor("#436EEE") ROYALBLUE3 = ManimColor("#3A5FCD") ROYALBLUE4 = ManimColor("#27408B") SADDLEBROWN = ManimColor("#8B4513") SALMON = ManimColor("#FA8072") SALMON1 = ManimColor("#FF8C69") SALMON2 = ManimColor("#EE8262") SALMON3 = ManimColor("#CD7054") SALMON4 = ManimColor("#8B4C39") SANDYBROWN = ManimColor("#F4A460") SEAGREEN1 = ManimColor("#54FF9F") SEAGREEN2 = ManimColor("#4EEE94") SEAGREEN3 = ManimColor("#43CD80") SEAGREEN4 = ManimColor("#2E8B57") SEASHELL1 = ManimColor("#FFF5EE") SEASHELL2 = ManimColor("#EEE5DE") SEASHELL3 = ManimColor("#CDC5BF") SEASHELL4 = ManimColor("#8B8682") SIENNA = ManimColor("#A0522D") SIENNA1 = ManimColor("#FF8247") SIENNA2 = ManimColor("#EE7942") SIENNA3 = ManimColor("#CD6839") SIENNA4 = ManimColor("#8B4726") SKYBLUE = ManimColor("#87CEEB") SKYBLUE1 = ManimColor("#87CEFF") SKYBLUE2 = ManimColor("#7EC0EE") SKYBLUE3 = ManimColor("#6CA6CD") SKYBLUE4 = ManimColor("#4A708B") SLATEBLUE = ManimColor("#6A5ACD") SLATEBLUE1 = ManimColor("#836FFF") SLATEBLUE2 = ManimColor("#7A67EE") SLATEBLUE3 = ManimColor("#6959CD") SLATEBLUE4 = ManimColor("#473C8B") SLATEGRAY = ManimColor("#708090") SLATEGRAY1 = ManimColor("#C6E2FF") SLATEGRAY2 = ManimColor("#B9D3EE") SLATEGRAY3 = ManimColor("#9FB6CD") SLATEGRAY4 = ManimColor("#6C7B8B") SNOW1 = ManimColor("#FFFAFA") SNOW2 = ManimColor("#EEE9E9") SNOW3 = ManimColor("#CDC9C9") SNOW4 = ManimColor("#8B8989") SPRINGGREEN1 = ManimColor("#00FF7F") SPRINGGREEN2 = ManimColor("#00EE76") SPRINGGREEN3 = ManimColor("#00CD66") SPRINGGREEN4 = ManimColor("#008B45") STEELBLUE = ManimColor("#4682B4") STEELBLUE1 = ManimColor("#63B8FF") STEELBLUE2 = ManimColor("#5CACEE") STEELBLUE3 = ManimColor("#4F94CD") STEELBLUE4 = ManimColor("#36648B") TAN = ManimColor("#D2B48C") TAN1 = ManimColor("#FFA54F") TAN2 = ManimColor("#EE9A49") TAN3 = ManimColor("#CD853F") TAN4 = ManimColor("#8B5A2B") THISTLE =
|
SNOW3 = ManimColor("#CDC9C9") SNOW4 = ManimColor("#8B8989") SPRINGGREEN1 = ManimColor("#00FF7F") SPRINGGREEN2 = ManimColor("#00EE76") SPRINGGREEN3 = ManimColor("#00CD66") SPRINGGREEN4 = ManimColor("#008B45") STEELBLUE = ManimColor("#4682B4") STEELBLUE1 = ManimColor("#63B8FF") STEELBLUE2 = ManimColor("#5CACEE") STEELBLUE3 = ManimColor("#4F94CD") STEELBLUE4 = ManimColor("#36648B") TAN = ManimColor("#D2B48C") TAN1 = ManimColor("#FFA54F") TAN2 = ManimColor("#EE9A49") TAN3 = ManimColor("#CD853F") TAN4 = ManimColor("#8B5A2B") THISTLE = ManimColor("#D8BFD8") THISTLE1 = ManimColor("#FFE1FF") THISTLE2 = ManimColor("#EED2EE") THISTLE3 = ManimColor("#CDB5CD") THISTLE4 = ManimColor("#8B7B8B") TOMATO1 = ManimColor("#FF6347") TOMATO2 = ManimColor("#EE5C42") TOMATO3 = ManimColor("#CD4F39") TOMATO4 = ManimColor("#8B3626") TURQUOISE = ManimColor("#40E0D0") TURQUOISE1 = ManimColor("#00F5FF") TURQUOISE2 = ManimColor("#00E5EE") TURQUOISE3 = ManimColor("#00C5CD") TURQUOISE4 = ManimColor("#00868B") VIOLET = ManimColor("#EE82EE") VIOLETRED = ManimColor("#D02090") VIOLETRED1 = ManimColor("#FF3E96") VIOLETRED2 = ManimColor("#EE3A8C") VIOLETRED3 = ManimColor("#CD3278") VIOLETRED4 = ManimColor("#8B2252") WHEAT = ManimColor("#F5DEB3") WHEAT1 = ManimColor("#FFE7BA") WHEAT2 = ManimColor("#EED8AE") WHEAT3 = ManimColor("#CDBA96") WHEAT4 = ManimColor("#8B7E66") WHITE = ManimColor("#FFFFFF") WHITESMOKE = ManimColor("#F5F5F5") YELLOW1 = ManimColor("#FFFF00") YELLOW2 = ManimColor("#EEEE00") YELLOW3 = ManimColor("#CDCD00") YELLOW4 = ManimColor("#8B8B00") YELLOWGREEN = ManimColor("#9ACD32") ================================================ FILE: manim/utils/color/XKCD.py ================================================ """Colors from the XKCD Color Name Survey XKCD is a popular `web comic <https://xkcd.com/353/>`__ created by Randall Munroe. His "`Color Name Survey <http://blog.xkcd.com/2010/05/03/color-survey-results/>`__" (with 200000 participants) resulted in a list of nearly 1000 color names. While the ``XKCD`` module is exposed to Manim's global name space, the colors included in it are not. This means that in order to use the colors, access them via the module name: .. code:: pycon >>> from manim import XKCD >>> XKCD.MANGO ManimColor('#FFA62B') List of Color Constants ----------------------- These hex values are non official approximate values intended to simulate the colors in HTML, taken from https://www.w3schools.com/colors/colors_xkcd.asp. .. automanimcolormodule:: manim.utils.color.XKCD """ from __future__ import annotations from .core import ManimColor ACIDGREEN = ManimColor("#8FFE09") ADOBE = ManimColor("#BD6C48") ALGAE = ManimColor("#54AC68") ALGAEGREEN = ManimColor("#21C36F") ALMOSTBLACK = ManimColor("#070D0D") AMBER = ManimColor("#FEB308") AMETHYST = ManimColor("#9B5FC0") APPLE = ManimColor("#6ECB3C") APPLEGREEN = ManimColor("#76CD26") APRICOT = ManimColor("#FFB16D") AQUA = ManimColor("#13EAC9") AQUABLUE = ManimColor("#02D8E9") AQUAGREEN = ManimColor("#12E193") AQUAMARINE = ManimColor("#2EE8BB") ARMYGREEN = ManimColor("#4B5D16") ASPARAGUS = ManimColor("#77AB56") AUBERGINE = ManimColor("#3D0734") AUBURN = ManimColor("#9A3001") AVOCADO = ManimColor("#90B134") AVOCADOGREEN = ManimColor("#87A922") AZUL = ManimColor("#1D5DEC") AZURE = ManimColor("#069AF3") BABYBLUE = ManimColor("#A2CFFE") BABYGREEN = ManimColor("#8CFF9E") BABYPINK = ManimColor("#FFB7CE") BABYPOO = ManimColor("#AB9004") BABYPOOP = ManimColor("#937C00") BABYPOOPGREEN = ManimColor("#8F9805") BABYPUKEGREEN = ManimColor("#B6C406") BABYPURPLE = ManimColor("#CA9BF7") BABYSHITBROWN = ManimColor("#AD900D") BABYSHITGREEN = ManimColor("#889717") BANANA = ManimColor("#FFFF7E") BANANAYELLOW = ManimColor("#FAFE4B") BARBIEPINK = ManimColor("#FE46A5") BARFGREEN = ManimColor("#94AC02") BARNEY = ManimColor("#AC1DB8") BARNEYPURPLE = ManimColor("#A00498") BATTLESHIPGREY = ManimColor("#6B7C85") BEIGE = ManimColor("#E6DAA6") BERRY = ManimColor("#990F4B") BILE = ManimColor("#B5C306") BLACK = ManimColor("#000000") BLAND = ManimColor("#AFA88B") BLOOD = ManimColor("#770001") BLOODORANGE = ManimColor("#FE4B03") BLOODRED = ManimColor("#980002") BLUE = ManimColor("#0343DF") BLUEBERRY = ManimColor("#464196") BLUEBLUE = ManimColor("#2242C7") BLUEGREEN = ManimColor("#0F9B8E") BLUEGREY = ManimColor("#85A3B2") BLUEPURPLE = ManimColor("#5A06EF") BLUEVIOLET = ManimColor("#5D06E9") BLUEWITHAHINTOFPURPLE = ManimColor("#533CC6") BLUEYGREEN = ManimColor("#2BB179") BLUEYGREY = ManimColor("#89A0B0") BLUEYPURPLE = ManimColor("#6241C7") BLUISH = ManimColor("#2976BB") BLUISHGREEN = ManimColor("#10A674") BLUISHGREY = ManimColor("#748B97") BLUISHPURPLE = ManimColor("#703BE7") BLURPLE = ManimColor("#5539CC") BLUSH = ManimColor("#F29E8E") BLUSHPINK = ManimColor("#FE828C") BOOGER = ManimColor("#9BB53C") BOOGERGREEN = ManimColor("#96B403") BORDEAUX = ManimColor("#7B002C") BORINGGREEN = ManimColor("#63B365") BOTTLEGREEN = ManimColor("#044A05") BRICK = ManimColor("#A03623") BRICKORANGE = ManimColor("#C14A09") BRICKRED = ManimColor("#8F1402") BRIGHTAQUA = ManimColor("#0BF9EA") BRIGHTBLUE = ManimColor("#0165FC") BRIGHTCYAN = ManimColor("#41FDFE") BRIGHTGREEN = ManimColor("#01FF07") BRIGHTLAVENDER = ManimColor("#C760FF") BRIGHTLIGHTBLUE = ManimColor("#26F7FD") BRIGHTLIGHTGREEN
|
ManimColor("#5539CC") BLUSH = ManimColor("#F29E8E") BLUSHPINK = ManimColor("#FE828C") BOOGER = ManimColor("#9BB53C") BOOGERGREEN = ManimColor("#96B403") BORDEAUX = ManimColor("#7B002C") BORINGGREEN = ManimColor("#63B365") BOTTLEGREEN = ManimColor("#044A05") BRICK = ManimColor("#A03623") BRICKORANGE = ManimColor("#C14A09") BRICKRED = ManimColor("#8F1402") BRIGHTAQUA = ManimColor("#0BF9EA") BRIGHTBLUE = ManimColor("#0165FC") BRIGHTCYAN = ManimColor("#41FDFE") BRIGHTGREEN = ManimColor("#01FF07") BRIGHTLAVENDER = ManimColor("#C760FF") BRIGHTLIGHTBLUE = ManimColor("#26F7FD") BRIGHTLIGHTGREEN = ManimColor("#2DFE54") BRIGHTLILAC = ManimColor("#C95EFB") BRIGHTLIME = ManimColor("#87FD05") BRIGHTLIMEGREEN = ManimColor("#65FE08") BRIGHTMAGENTA = ManimColor("#FF08E8") BRIGHTOLIVE = ManimColor("#9CBB04") BRIGHTORANGE = ManimColor("#FF5B00") BRIGHTPINK = ManimColor("#FE01B1") BRIGHTPURPLE = ManimColor("#BE03FD") BRIGHTRED = ManimColor("#FF000D") BRIGHTSEAGREEN = ManimColor("#05FFA6") BRIGHTSKYBLUE = ManimColor("#02CCFE") BRIGHTTEAL = ManimColor("#01F9C6") BRIGHTTURQUOISE = ManimColor("#0FFEF9") BRIGHTVIOLET = ManimColor("#AD0AFD") BRIGHTYELLOW = ManimColor("#FFFD01") BRIGHTYELLOWGREEN = ManimColor("#9DFF00") BRITISHRACINGGREEN = ManimColor("#05480D") BRONZE = ManimColor("#A87900") BROWN = ManimColor("#653700") BROWNGREEN = ManimColor("#706C11") BROWNGREY = ManimColor("#8D8468") BROWNISH = ManimColor("#9C6D57") BROWNISHGREEN = ManimColor("#6A6E09") BROWNISHGREY = ManimColor("#86775F") BROWNISHORANGE = ManimColor("#CB7723") BROWNISHPINK = ManimColor("#C27E79") BROWNISHPURPLE = ManimColor("#76424E") BROWNISHRED = ManimColor("#9E3623") BROWNISHYELLOW = ManimColor("#C9B003") BROWNORANGE = ManimColor("#B96902") BROWNRED = ManimColor("#922B05") BROWNYELLOW = ManimColor("#B29705") BROWNYGREEN = ManimColor("#6F6C0A") BROWNYORANGE = ManimColor("#CA6B02") BRUISE = ManimColor("#7E4071") BUBBLEGUM = ManimColor("#FF6CB5") BUBBLEGUMPINK = ManimColor("#FF69AF") BUFF = ManimColor("#FEF69E") BURGUNDY = ManimColor("#610023") BURNTORANGE = ManimColor("#C04E01") BURNTRED = ManimColor("#9F2305") BURNTSIENA = ManimColor("#B75203") BURNTSIENNA = ManimColor("#B04E0F") BURNTUMBER = ManimColor("#A0450E") BURNTYELLOW = ManimColor("#D5AB09") BURPLE = ManimColor("#6832E3") BUTTER = ManimColor("#FFFF81") BUTTERSCOTCH = ManimColor("#FDB147") BUTTERYELLOW = ManimColor("#FFFD74") CADETBLUE = ManimColor("#4E7496") CAMEL = ManimColor("#C69F59") CAMO = ManimColor("#7F8F4E") CAMOGREEN = ManimColor("#526525") CAMOUFLAGEGREEN = ManimColor("#4B6113") CANARY = ManimColor("#FDFF63") CANARYYELLOW = ManimColor("#FFFE40") CANDYPINK = ManimColor("#FF63E9") CARAMEL = ManimColor("#AF6F09") CARMINE = ManimColor("#9D0216") CARNATION = ManimColor("#FD798F") CARNATIONPINK = ManimColor("#FF7FA7") CAROLINABLUE = ManimColor("#8AB8FE") CELADON = ManimColor("#BEFDB7") CELERY = ManimColor("#C1FD95") CEMENT = ManimColor("#A5A391") CERISE = ManimColor("#DE0C62") CERULEAN = ManimColor("#0485D1") CERULEANBLUE = ManimColor("#056EEE") CHARCOAL = ManimColor("#343837") CHARCOALGREY = ManimColor("#3C4142") CHARTREUSE = ManimColor("#C1F80A") CHERRY = ManimColor("#CF0234") CHERRYRED = ManimColor("#F7022A") CHESTNUT = ManimColor("#742802") CHOCOLATE = ManimColor("#3D1C02") CHOCOLATEBROWN = ManimColor("#411900") CINNAMON = ManimColor("#AC4F06") CLARET = ManimColor("#680018") CLAY = ManimColor("#B66A50") CLAYBROWN = ManimColor("#B2713D") CLEARBLUE = ManimColor("#247AFD") COBALT = ManimColor("#1E488F") COBALTBLUE = ManimColor("#030AA7") COCOA = ManimColor("#875F42") COFFEE = ManimColor("#A6814C") COOLBLUE = ManimColor("#4984B8") COOLGREEN = ManimColor("#33B864") COOLGREY = ManimColor("#95A3A6") COPPER = ManimColor("#B66325") CORAL = ManimColor("#FC5A50") CORALPINK = ManimColor("#FF6163") CORNFLOWER = ManimColor("#6A79F7") CORNFLOWERBLUE = ManimColor("#5170D7") CRANBERRY = ManimColor("#9E003A") CREAM = ManimColor("#FFFFC2") CREME = ManimColor("#FFFFB6") CRIMSON = ManimColor("#8C000F") CUSTARD = ManimColor("#FFFD78") CYAN = ManimColor("#00FFFF") DANDELION = ManimColor("#FEDF08") DARK = ManimColor("#1B2431") DARKAQUA = ManimColor("#05696B") DARKAQUAMARINE = ManimColor("#017371") DARKBEIGE = ManimColor("#AC9362") DARKBLUE = ManimColor("#030764") DARKBLUEGREEN = ManimColor("#005249") DARKBLUEGREY = ManimColor("#1F3B4D") DARKBROWN = ManimColor("#341C02") DARKCORAL = ManimColor("#CF524E") DARKCREAM = ManimColor("#FFF39A") DARKCYAN = ManimColor("#0A888A") DARKFORESTGREEN = ManimColor("#002D04") DARKFUCHSIA = ManimColor("#9D0759") DARKGOLD = ManimColor("#B59410") DARKGRASSGREEN = ManimColor("#388004") DARKGREEN = ManimColor("#054907") DARKGREENBLUE = ManimColor("#1F6357") DARKGREY = ManimColor("#363737") DARKGREYBLUE = ManimColor("#29465B") DARKHOTPINK = ManimColor("#D90166") DARKINDIGO = ManimColor("#1F0954") DARKISHBLUE = ManimColor("#014182") DARKISHGREEN = ManimColor("#287C37") DARKISHPINK = ManimColor("#DA467D") DARKISHPURPLE = ManimColor("#751973") DARKISHRED = ManimColor("#A90308") DARKKHAKI = ManimColor("#9B8F55") DARKLAVENDER = ManimColor("#856798") DARKLILAC = ManimColor("#9C6DA5") DARKLIME = ManimColor("#84B701") DARKLIMEGREEN = ManimColor("#7EBD01") DARKMAGENTA = ManimColor("#960056") DARKMAROON = ManimColor("#3C0008") DARKMAUVE = ManimColor("#874C62") DARKMINT = ManimColor("#48C072") DARKMINTGREEN = ManimColor("#20C073") DARKMUSTARD = ManimColor("#A88905") DARKNAVY = ManimColor("#000435") DARKNAVYBLUE = ManimColor("#00022E") DARKOLIVE = ManimColor("#373E02") DARKOLIVEGREEN = ManimColor("#3C4D03") DARKORANGE = ManimColor("#C65102") DARKPASTELGREEN = ManimColor("#56AE57") DARKPEACH = ManimColor("#DE7E5D") DARKPERIWINKLE = ManimColor("#665FD1") DARKPINK = ManimColor("#CB416B") DARKPLUM = ManimColor("#3F012C") DARKPURPLE = ManimColor("#35063E") DARKRED = ManimColor("#840000") DARKROSE
|
ManimColor("#3C0008") DARKMAUVE = ManimColor("#874C62") DARKMINT = ManimColor("#48C072") DARKMINTGREEN = ManimColor("#20C073") DARKMUSTARD = ManimColor("#A88905") DARKNAVY = ManimColor("#000435") DARKNAVYBLUE = ManimColor("#00022E") DARKOLIVE = ManimColor("#373E02") DARKOLIVEGREEN = ManimColor("#3C4D03") DARKORANGE = ManimColor("#C65102") DARKPASTELGREEN = ManimColor("#56AE57") DARKPEACH = ManimColor("#DE7E5D") DARKPERIWINKLE = ManimColor("#665FD1") DARKPINK = ManimColor("#CB416B") DARKPLUM = ManimColor("#3F012C") DARKPURPLE = ManimColor("#35063E") DARKRED = ManimColor("#840000") DARKROSE = ManimColor("#B5485D") DARKROYALBLUE = ManimColor("#02066F") DARKSAGE = ManimColor("#598556") DARKSALMON = ManimColor("#C85A53") DARKSAND = ManimColor("#A88F59") DARKSEAFOAM = ManimColor("#1FB57A") DARKSEAFOAMGREEN = ManimColor("#3EAF76") DARKSEAGREEN = ManimColor("#11875D") DARKSKYBLUE = ManimColor("#448EE4") DARKSLATEBLUE = ManimColor("#214761") DARKTAN = ManimColor("#AF884A") DARKTAUPE = ManimColor("#7F684E") DARKTEAL = ManimColor("#014D4E") DARKTURQUOISE = ManimColor("#045C5A") DARKVIOLET = ManimColor("#34013F") DARKYELLOW = ManimColor("#D5B60A") DARKYELLOWGREEN = ManimColor("#728F02") DEEPAQUA = ManimColor("#08787F") DEEPBLUE = ManimColor("#040273") DEEPBROWN = ManimColor("#410200") DEEPGREEN = ManimColor("#02590F") DEEPLAVENDER = ManimColor("#8D5EB7") DEEPLILAC = ManimColor("#966EBD") DEEPMAGENTA = ManimColor("#A0025C") DEEPORANGE = ManimColor("#DC4D01") DEEPPINK = ManimColor("#CB0162") DEEPPURPLE = ManimColor("#36013F") DEEPRED = ManimColor("#9A0200") DEEPROSE = ManimColor("#C74767") DEEPSEABLUE = ManimColor("#015482") DEEPSKYBLUE = ManimColor("#0D75F8") DEEPTEAL = ManimColor("#00555A") DEEPTURQUOISE = ManimColor("#017374") DEEPVIOLET = ManimColor("#490648") DENIM = ManimColor("#3B638C") DENIMBLUE = ManimColor("#3B5B92") DESERT = ManimColor("#CCAD60") DIARRHEA = ManimColor("#9F8303") DIRT = ManimColor("#8A6E45") DIRTBROWN = ManimColor("#836539") DIRTYBLUE = ManimColor("#3F829D") DIRTYGREEN = ManimColor("#667E2C") DIRTYORANGE = ManimColor("#C87606") DIRTYPINK = ManimColor("#CA7B80") DIRTYPURPLE = ManimColor("#734A65") DIRTYYELLOW = ManimColor("#CDC50A") DODGERBLUE = ManimColor("#3E82FC") DRAB = ManimColor("#828344") DRABGREEN = ManimColor("#749551") DRIEDBLOOD = ManimColor("#4B0101") DUCKEGGBLUE = ManimColor("#C3FBF4") DULLBLUE = ManimColor("#49759C") DULLBROWN = ManimColor("#876E4B") DULLGREEN = ManimColor("#74A662") DULLORANGE = ManimColor("#D8863B") DULLPINK = ManimColor("#D5869D") DULLPURPLE = ManimColor("#84597E") DULLRED = ManimColor("#BB3F3F") DULLTEAL = ManimColor("#5F9E8F") DULLYELLOW = ManimColor("#EEDC5B") DUSK = ManimColor("#4E5481") DUSKBLUE = ManimColor("#26538D") DUSKYBLUE = ManimColor("#475F94") DUSKYPINK = ManimColor("#CC7A8B") DUSKYPURPLE = ManimColor("#895B7B") DUSKYROSE = ManimColor("#BA6873") DUST = ManimColor("#B2996E") DUSTYBLUE = ManimColor("#5A86AD") DUSTYGREEN = ManimColor("#76A973") DUSTYLAVENDER = ManimColor("#AC86A8") DUSTYORANGE = ManimColor("#F0833A") DUSTYPINK = ManimColor("#D58A94") DUSTYPURPLE = ManimColor("#825F87") DUSTYRED = ManimColor("#B9484E") DUSTYROSE = ManimColor("#C0737A") DUSTYTEAL = ManimColor("#4C9085") EARTH = ManimColor("#A2653E") EASTERGREEN = ManimColor("#8CFD7E") EASTERPURPLE = ManimColor("#C071FE") ECRU = ManimColor("#FEFFCA") EGGPLANT = ManimColor("#380835") EGGPLANTPURPLE = ManimColor("#430541") EGGSHELL = ManimColor("#FFFCC4") EGGSHELLBLUE = ManimColor("#C4FFF7") ELECTRICBLUE = ManimColor("#0652FF") ELECTRICGREEN = ManimColor("#21FC0D") ELECTRICLIME = ManimColor("#A8FF04") ELECTRICPINK = ManimColor("#FF0490") ELECTRICPURPLE = ManimColor("#AA23FF") EMERALD = ManimColor("#01A049") EMERALDGREEN = ManimColor("#028F1E") EVERGREEN = ManimColor("#05472A") FADEDBLUE = ManimColor("#658CBB") FADEDGREEN = ManimColor("#7BB274") FADEDORANGE = ManimColor("#F0944D") FADEDPINK = ManimColor("#DE9DAC") FADEDPURPLE = ManimColor("#916E99") FADEDRED = ManimColor("#D3494E") FADEDYELLOW = ManimColor("#FEFF7F") FAWN = ManimColor("#CFAF7B") FERN = ManimColor("#63A950") FERNGREEN = ManimColor("#548D44") FIREENGINERED = ManimColor("#FE0002") FLATBLUE = ManimColor("#3C73A8") FLATGREEN = ManimColor("#699D4C") FLUORESCENTGREEN = ManimColor("#08FF08") FLUROGREEN = ManimColor("#0AFF02") FOAMGREEN = ManimColor("#90FDA9") FOREST = ManimColor("#0B5509") FORESTGREEN = ManimColor("#06470C") FORRESTGREEN = ManimColor("#154406") FRENCHBLUE = ManimColor("#436BAD") FRESHGREEN = ManimColor("#69D84F") FROGGREEN = ManimColor("#58BC08") FUCHSIA = ManimColor("#ED0DD9") GOLD = ManimColor("#DBB40C") GOLDEN = ManimColor("#F5BF03") GOLDENBROWN = ManimColor("#B27A01") GOLDENROD = ManimColor("#F9BC08") GOLDENYELLOW = ManimColor("#FEC615") GRAPE = ManimColor("#6C3461") GRAPEFRUIT = ManimColor("#FD5956") GRAPEPURPLE = ManimColor("#5D1451") GRASS = ManimColor("#5CAC2D") GRASSGREEN = ManimColor("#3F9B0B") GRASSYGREEN = ManimColor("#419C03") GREEN = ManimColor("#15B01A") GREENAPPLE = ManimColor("#5EDC1F") GREENBLUE = ManimColor("#01C08D") GREENBROWN = ManimColor("#544E03") GREENGREY = ManimColor("#77926F") GREENISH = ManimColor("#40A368") GREENISHBEIGE = ManimColor("#C9D179") GREENISHBLUE = ManimColor("#0B8B87") GREENISHBROWN = ManimColor("#696112") GREENISHCYAN = ManimColor("#2AFEB7") GREENISHGREY = ManimColor("#96AE8D") GREENISHTAN = ManimColor("#BCCB7A") GREENISHTEAL = ManimColor("#32BF84") GREENISHTURQUOISE = ManimColor("#00FBB0") GREENISHYELLOW = ManimColor("#CDFD02") GREENTEAL = ManimColor("#0CB577") GREENYBLUE = ManimColor("#42B395") GREENYBROWN = ManimColor("#696006") GREENYELLOW = ManimColor("#B5CE08") GREENYGREY = ManimColor("#7EA07A") GREENYYELLOW = ManimColor("#C6F808") GREY = ManimColor("#929591") GREYBLUE = ManimColor("#647D8E") GREYBROWN = ManimColor("#7F7053") GREYGREEN
|
ManimColor("#0B8B87") GREENISHBROWN = ManimColor("#696112") GREENISHCYAN = ManimColor("#2AFEB7") GREENISHGREY = ManimColor("#96AE8D") GREENISHTAN = ManimColor("#BCCB7A") GREENISHTEAL = ManimColor("#32BF84") GREENISHTURQUOISE = ManimColor("#00FBB0") GREENISHYELLOW = ManimColor("#CDFD02") GREENTEAL = ManimColor("#0CB577") GREENYBLUE = ManimColor("#42B395") GREENYBROWN = ManimColor("#696006") GREENYELLOW = ManimColor("#B5CE08") GREENYGREY = ManimColor("#7EA07A") GREENYYELLOW = ManimColor("#C6F808") GREY = ManimColor("#929591") GREYBLUE = ManimColor("#647D8E") GREYBROWN = ManimColor("#7F7053") GREYGREEN = ManimColor("#86A17D") GREYISH = ManimColor("#A8A495") GREYISHBLUE = ManimColor("#5E819D") GREYISHBROWN = ManimColor("#7A6A4F") GREYISHGREEN = ManimColor("#82A67D") GREYISHPINK = ManimColor("#C88D94") GREYISHPURPLE = ManimColor("#887191") GREYISHTEAL = ManimColor("#719F91") GREYPINK = ManimColor("#C3909B") GREYPURPLE = ManimColor("#826D8C") GREYTEAL = ManimColor("#5E9B8A") GROSSGREEN = ManimColor("#A0BF16") GUNMETAL = ManimColor("#536267") HAZEL = ManimColor("#8E7618") HEATHER = ManimColor("#A484AC") HELIOTROPE = ManimColor("#D94FF5") HIGHLIGHTERGREEN = ManimColor("#1BFC06") HOSPITALGREEN = ManimColor("#9BE5AA") HOTGREEN = ManimColor("#25FF29") HOTMAGENTA = ManimColor("#F504C9") HOTPINK = ManimColor("#FF028D") HOTPURPLE = ManimColor("#CB00F5") HUNTERGREEN = ManimColor("#0B4008") ICE = ManimColor("#D6FFFA") ICEBLUE = ManimColor("#D7FFFE") ICKYGREEN = ManimColor("#8FAE22") INDIANRED = ManimColor("#850E04") INDIGO = ManimColor("#380282") INDIGOBLUE = ManimColor("#3A18B1") IRIS = ManimColor("#6258C4") IRISHGREEN = ManimColor("#019529") IVORY = ManimColor("#FFFFCB") JADE = ManimColor("#1FA774") JADEGREEN = ManimColor("#2BAF6A") JUNGLEGREEN = ManimColor("#048243") KELLEYGREEN = ManimColor("#009337") KELLYGREEN = ManimColor("#02AB2E") KERMITGREEN = ManimColor("#5CB200") KEYLIME = ManimColor("#AEFF6E") KHAKI = ManimColor("#AAA662") KHAKIGREEN = ManimColor("#728639") KIWI = ManimColor("#9CEF43") KIWIGREEN = ManimColor("#8EE53F") LAVENDER = ManimColor("#C79FEF") LAVENDERBLUE = ManimColor("#8B88F8") LAVENDERPINK = ManimColor("#DD85D7") LAWNGREEN = ManimColor("#4DA409") LEAF = ManimColor("#71AA34") LEAFGREEN = ManimColor("#5CA904") LEAFYGREEN = ManimColor("#51B73B") LEATHER = ManimColor("#AC7434") LEMON = ManimColor("#FDFF52") LEMONGREEN = ManimColor("#ADF802") LEMONLIME = ManimColor("#BFFE28") LEMONYELLOW = ManimColor("#FDFF38") LICHEN = ManimColor("#8FB67B") LIGHTAQUA = ManimColor("#8CFFDB") LIGHTAQUAMARINE = ManimColor("#7BFDC7") LIGHTBEIGE = ManimColor("#FFFEB6") LIGHTBLUE = ManimColor("#7BC8F6") LIGHTBLUEGREEN = ManimColor("#7EFBB3") LIGHTBLUEGREY = ManimColor("#B7C9E2") LIGHTBLUISHGREEN = ManimColor("#76FDA8") LIGHTBRIGHTGREEN = ManimColor("#53FE5C") LIGHTBROWN = ManimColor("#AD8150") LIGHTBURGUNDY = ManimColor("#A8415B") LIGHTCYAN = ManimColor("#ACFFFC") LIGHTEGGPLANT = ManimColor("#894585") LIGHTERGREEN = ManimColor("#75FD63") LIGHTERPURPLE = ManimColor("#A55AF4") LIGHTFORESTGREEN = ManimColor("#4F9153") LIGHTGOLD = ManimColor("#FDDC5C") LIGHTGRASSGREEN = ManimColor("#9AF764") LIGHTGREEN = ManimColor("#76FF7B") LIGHTGREENBLUE = ManimColor("#56FCA2") LIGHTGREENISHBLUE = ManimColor("#63F7B4") LIGHTGREY = ManimColor("#D8DCD6") LIGHTGREYBLUE = ManimColor("#9DBCD4") LIGHTGREYGREEN = ManimColor("#B7E1A1") LIGHTINDIGO = ManimColor("#6D5ACF") LIGHTISHBLUE = ManimColor("#3D7AFD") LIGHTISHGREEN = ManimColor("#61E160") LIGHTISHPURPLE = ManimColor("#A552E6") LIGHTISHRED = ManimColor("#FE2F4A") LIGHTKHAKI = ManimColor("#E6F2A2") LIGHTLAVENDAR = ManimColor("#EFC0FE") LIGHTLAVENDER = ManimColor("#DFC5FE") LIGHTLIGHTBLUE = ManimColor("#CAFFFB") LIGHTLIGHTGREEN = ManimColor("#C8FFB0") LIGHTLILAC = ManimColor("#EDC8FF") LIGHTLIME = ManimColor("#AEFD6C") LIGHTLIMEGREEN = ManimColor("#B9FF66") LIGHTMAGENTA = ManimColor("#FA5FF7") LIGHTMAROON = ManimColor("#A24857") LIGHTMAUVE = ManimColor("#C292A1") LIGHTMINT = ManimColor("#B6FFBB") LIGHTMINTGREEN = ManimColor("#A6FBB2") LIGHTMOSSGREEN = ManimColor("#A6C875") LIGHTMUSTARD = ManimColor("#F7D560") LIGHTNAVY = ManimColor("#155084") LIGHTNAVYBLUE = ManimColor("#2E5A88") LIGHTNEONGREEN = ManimColor("#4EFD54") LIGHTOLIVE = ManimColor("#ACBF69") LIGHTOLIVEGREEN = ManimColor("#A4BE5C") LIGHTORANGE = ManimColor("#FDAA48") LIGHTPASTELGREEN = ManimColor("#B2FBA5") LIGHTPEACH = ManimColor("#FFD8B1") LIGHTPEAGREEN = ManimColor("#C4FE82") LIGHTPERIWINKLE = ManimColor("#C1C6FC") LIGHTPINK = ManimColor("#FFD1DF") LIGHTPLUM = ManimColor("#9D5783") LIGHTPURPLE = ManimColor("#BF77F6") LIGHTRED = ManimColor("#FF474C") LIGHTROSE = ManimColor("#FFC5CB") LIGHTROYALBLUE = ManimColor("#3A2EFE") LIGHTSAGE = ManimColor("#BCECAC") LIGHTSALMON = ManimColor("#FEA993") LIGHTSEAFOAM = ManimColor("#A0FEBF") LIGHTSEAFOAMGREEN = ManimColor("#a7ffb5") LIGHTSEAGREEN = ManimColor("#98F6B0") LIGHTSKYBLUE = ManimColor("#C6FCFF") LIGHTTAN = ManimColor("#FBEEAC") LIGHTTEAL = ManimColor("#90E4C1") LIGHTTURQUOISE = ManimColor("#7EF4CC") LIGHTURPLE = ManimColor("#B36FF6") LIGHTVIOLET = ManimColor("#D6B4FC") LIGHTYELLOW = ManimColor("#FFFE7A") LIGHTYELLOWGREEN = ManimColor("#CCFD7F") LIGHTYELLOWISHGREEN = ManimColor("#C2FF89") LILAC = ManimColor("#CEA2FD") LILIAC = ManimColor("#C48EFD") LIME = ManimColor("#AAFF32") LIMEGREEN = ManimColor("#89FE05") LIMEYELLOW = ManimColor("#D0FE1D") LIPSTICK = ManimColor("#D5174E") LIPSTICKRED = ManimColor("#C0022F") MACARONIANDCHEESE = ManimColor("#EFB435") MAGENTA = ManimColor("#C20078") MAHOGANY = ManimColor("#4A0100") MAIZE = ManimColor("#F4D054") MANGO = ManimColor("#FFA62B") MANILLA = ManimColor("#FFFA86") MARIGOLD = ManimColor("#FCC006") MARINE = ManimColor("#042E60") MARINEBLUE = ManimColor("#01386A") MAROON = ManimColor("#650021") MAUVE = ManimColor("#AE7181") MEDIUMBLUE = ManimColor("#2C6FBB") MEDIUMBROWN = ManimColor("#7F5112") MEDIUMGREEN = ManimColor("#39AD48") MEDIUMGREY
|
ManimColor("#D0FE1D") LIPSTICK = ManimColor("#D5174E") LIPSTICKRED = ManimColor("#C0022F") MACARONIANDCHEESE = ManimColor("#EFB435") MAGENTA = ManimColor("#C20078") MAHOGANY = ManimColor("#4A0100") MAIZE = ManimColor("#F4D054") MANGO = ManimColor("#FFA62B") MANILLA = ManimColor("#FFFA86") MARIGOLD = ManimColor("#FCC006") MARINE = ManimColor("#042E60") MARINEBLUE = ManimColor("#01386A") MAROON = ManimColor("#650021") MAUVE = ManimColor("#AE7181") MEDIUMBLUE = ManimColor("#2C6FBB") MEDIUMBROWN = ManimColor("#7F5112") MEDIUMGREEN = ManimColor("#39AD48") MEDIUMGREY = ManimColor("#7D7F7C") MEDIUMPINK = ManimColor("#F36196") MEDIUMPURPLE = ManimColor("#9E43A2") MELON = ManimColor("#FF7855") MERLOT = ManimColor("#730039") METALLICBLUE = ManimColor("#4F738E") MIDBLUE = ManimColor("#276AB3") MIDGREEN = ManimColor("#50A747") MIDNIGHT = ManimColor("#03012D") MIDNIGHTBLUE = ManimColor("#020035") MIDNIGHTPURPLE = ManimColor("#280137") MILITARYGREEN = ManimColor("#667C3E") MILKCHOCOLATE = ManimColor("#7F4E1E") MINT = ManimColor("#9FFEB0") MINTGREEN = ManimColor("#8FFF9F") MINTYGREEN = ManimColor("#0BF77D") MOCHA = ManimColor("#9D7651") MOSS = ManimColor("#769958") MOSSGREEN = ManimColor("#658B38") MOSSYGREEN = ManimColor("#638B27") MUD = ManimColor("#735C12") MUDBROWN = ManimColor("#60460F") MUDDYBROWN = ManimColor("#886806") MUDDYGREEN = ManimColor("#657432") MUDDYYELLOW = ManimColor("#BFAC05") MUDGREEN = ManimColor("#606602") MULBERRY = ManimColor("#920A4E") MURKYGREEN = ManimColor("#6C7A0E") MUSHROOM = ManimColor("#BA9E88") MUSTARD = ManimColor("#CEB301") MUSTARDBROWN = ManimColor("#AC7E04") MUSTARDGREEN = ManimColor("#A8B504") MUSTARDYELLOW = ManimColor("#D2BD0A") MUTEDBLUE = ManimColor("#3B719F") MUTEDGREEN = ManimColor("#5FA052") MUTEDPINK = ManimColor("#D1768F") MUTEDPURPLE = ManimColor("#805B87") NASTYGREEN = ManimColor("#70B23F") NAVY = ManimColor("#01153E") NAVYBLUE = ManimColor("#001146") NAVYGREEN = ManimColor("#35530A") NEONBLUE = ManimColor("#04D9FF") NEONGREEN = ManimColor("#0CFF0C") NEONPINK = ManimColor("#FE019A") NEONPURPLE = ManimColor("#BC13FE") NEONRED = ManimColor("#FF073A") NEONYELLOW = ManimColor("#CFFF04") NICEBLUE = ManimColor("#107AB0") NIGHTBLUE = ManimColor("#040348") OCEAN = ManimColor("#017B92") OCEANBLUE = ManimColor("#03719C") OCEANGREEN = ManimColor("#3D9973") OCHER = ManimColor("#BF9B0C") OCHRE = ManimColor("#BF9005") OCRE = ManimColor("#C69C04") OFFBLUE = ManimColor("#5684AE") OFFGREEN = ManimColor("#6BA353") OFFWHITE = ManimColor("#FFFFE4") OFFYELLOW = ManimColor("#F1F33F") OLDPINK = ManimColor("#C77986") OLDROSE = ManimColor("#C87F89") OLIVE = ManimColor("#6E750E") OLIVEBROWN = ManimColor("#645403") OLIVEDRAB = ManimColor("#6F7632") OLIVEGREEN = ManimColor("#677A04") OLIVEYELLOW = ManimColor("#C2B709") ORANGE = ManimColor("#F97306") ORANGEBROWN = ManimColor("#BE6400") ORANGEISH = ManimColor("#FD8D49") ORANGEPINK = ManimColor("#FF6F52") ORANGERED = ManimColor("#FE420F") ORANGEYBROWN = ManimColor("#B16002") ORANGEYELLOW = ManimColor("#FFAD01") ORANGEYRED = ManimColor("#FA4224") ORANGEYYELLOW = ManimColor("#FDB915") ORANGISH = ManimColor("#FC824A") ORANGISHBROWN = ManimColor("#B25F03") ORANGISHRED = ManimColor("#F43605") ORCHID = ManimColor("#C875C4") PALE = ManimColor("#FFF9D0") PALEAQUA = ManimColor("#B8FFEB") PALEBLUE = ManimColor("#D0FEFE") PALEBROWN = ManimColor("#B1916E") PALECYAN = ManimColor("#B7FFFA") PALEGOLD = ManimColor("#FDDE6C") PALEGREEN = ManimColor("#C7FDB5") PALEGREY = ManimColor("#FDFDFE") PALELAVENDER = ManimColor("#EECFFE") PALELIGHTGREEN = ManimColor("#B1FC99") PALELILAC = ManimColor("#E4CBFF") PALELIME = ManimColor("#BEFD73") PALELIMEGREEN = ManimColor("#B1FF65") PALEMAGENTA = ManimColor("#D767AD") PALEMAUVE = ManimColor("#FED0FC") PALEOLIVE = ManimColor("#B9CC81") PALEOLIVEGREEN = ManimColor("#B1D27B") PALEORANGE = ManimColor("#FFA756") PALEPEACH = ManimColor("#FFE5AD") PALEPINK = ManimColor("#FFCFDC") PALEPURPLE = ManimColor("#B790D4") PALERED = ManimColor("#D9544D") PALEROSE = ManimColor("#FDC1C5") PALESALMON = ManimColor("#FFB19A") PALESKYBLUE = ManimColor("#BDF6FE") PALETEAL = ManimColor("#82CBB2") PALETURQUOISE = ManimColor("#A5FBD5") PALEVIOLET = ManimColor("#CEAEFA") PALEYELLOW = ManimColor("#FFFF84") PARCHMENT = ManimColor("#FEFCAF") PASTELBLUE = ManimColor("#A2BFFE") PASTELGREEN = ManimColor("#B0FF9D") PASTELORANGE = ManimColor("#FF964F") PASTELPINK = ManimColor("#FFBACD") PASTELPURPLE = ManimColor("#CAA0FF") PASTELRED = ManimColor("#DB5856") PASTELYELLOW = ManimColor("#FFFE71") PEA = ManimColor("#A4BF20") PEACH = ManimColor("#FFB07C") PEACHYPINK = ManimColor("#FF9A8A") PEACOCKBLUE = ManimColor("#016795") PEAGREEN = ManimColor("#8EAB12") PEAR = ManimColor("#CBF85F") PEASOUP = ManimColor("#929901") PEASOUPGREEN = ManimColor("#94A617") PERIWINKLE = ManimColor("#8E82FE") PERIWINKLEBLUE = ManimColor("#8F99FB") PERRYWINKLE = ManimColor("#8F8CE7") PETROL = ManimColor("#005F6A") PIGPINK = ManimColor("#E78EA5") PINE = ManimColor("#2B5D34") PINEGREEN = ManimColor("#0A481E") PINK = ManimColor("#FF81C0") PINKISH = ManimColor("#D46A7E") PINKISHBROWN = ManimColor("#B17261") PINKISHGREY = ManimColor("#C8ACA9") PINKISHORANGE = ManimColor("#FF724C") PINKISHPURPLE = ManimColor("#D648D7") PINKISHRED = ManimColor("#F10C45") PINKISHTAN = ManimColor("#D99B82") PINKPURPLE = ManimColor("#EF1DE7") PINKRED = ManimColor("#F5054F") PINKY = ManimColor("#FC86AA") PINKYPURPLE = ManimColor("#C94CBE") PINKYRED = ManimColor("#FC2647") PISSYELLOW = ManimColor("#DDD618") PISTACHIO = ManimColor("#C0FA8B") PLUM = ManimColor("#580F41") PLUMPURPLE = ManimColor("#4E0550") POISONGREEN = ManimColor("#40FD14") POO = ManimColor("#8F7303") POOBROWN
|
ManimColor("#B17261") PINKISHGREY = ManimColor("#C8ACA9") PINKISHORANGE = ManimColor("#FF724C") PINKISHPURPLE = ManimColor("#D648D7") PINKISHRED = ManimColor("#F10C45") PINKISHTAN = ManimColor("#D99B82") PINKPURPLE = ManimColor("#EF1DE7") PINKRED = ManimColor("#F5054F") PINKY = ManimColor("#FC86AA") PINKYPURPLE = ManimColor("#C94CBE") PINKYRED = ManimColor("#FC2647") PISSYELLOW = ManimColor("#DDD618") PISTACHIO = ManimColor("#C0FA8B") PLUM = ManimColor("#580F41") PLUMPURPLE = ManimColor("#4E0550") POISONGREEN = ManimColor("#40FD14") POO = ManimColor("#8F7303") POOBROWN = ManimColor("#885F01") POOP = ManimColor("#7F5E00") POOPBROWN = ManimColor("#7A5901") POOPGREEN = ManimColor("#6F7C00") POWDERBLUE = ManimColor("#B1D1FC") POWDERPINK = ManimColor("#FFB2D0") PRIMARYBLUE = ManimColor("#0804F9") PRUSSIANBLUE = ManimColor("#004577") PUCE = ManimColor("#A57E52") PUKE = ManimColor("#A5A502") PUKEBROWN = ManimColor("#947706") PUKEGREEN = ManimColor("#9AAE07") PUKEYELLOW = ManimColor("#C2BE0E") PUMPKIN = ManimColor("#E17701") PUMPKINORANGE = ManimColor("#FB7D07") PUREBLUE = ManimColor("#0203E2") PURPLE = ManimColor("#7E1E9C") PURPLEBLUE = ManimColor("#5D21D0") PURPLEBROWN = ManimColor("#673A3F") PURPLEGREY = ManimColor("#866F85") PURPLEISH = ManimColor("#98568D") PURPLEISHBLUE = ManimColor("#6140EF") PURPLEISHPINK = ManimColor("#DF4EC8") PURPLEPINK = ManimColor("#D725DE") PURPLERED = ManimColor("#990147") PURPLEY = ManimColor("#8756E4") PURPLEYBLUE = ManimColor("#5F34E7") PURPLEYGREY = ManimColor("#947E94") PURPLEYPINK = ManimColor("#C83CB9") PURPLISH = ManimColor("#94568C") PURPLISHBLUE = ManimColor("#601EF9") PURPLISHBROWN = ManimColor("#6B4247") PURPLISHGREY = ManimColor("#7A687F") PURPLISHPINK = ManimColor("#CE5DAE") PURPLISHRED = ManimColor("#B0054B") PURPLY = ManimColor("#983FB2") PURPLYBLUE = ManimColor("#661AEE") PURPLYPINK = ManimColor("#F075E6") PUTTY = ManimColor("#BEAE8A") RACINGGREEN = ManimColor("#014600") RADIOACTIVEGREEN = ManimColor("#2CFA1F") RASPBERRY = ManimColor("#B00149") RAWSIENNA = ManimColor("#9A6200") RAWUMBER = ManimColor("#A75E09") REALLYLIGHTBLUE = ManimColor("#D4FFFF") RED = ManimColor("#E50000") REDBROWN = ManimColor("#8B2E16") REDDISH = ManimColor("#C44240") REDDISHBROWN = ManimColor("#7F2B0A") REDDISHGREY = ManimColor("#997570") REDDISHORANGE = ManimColor("#F8481C") REDDISHPINK = ManimColor("#FE2C54") REDDISHPURPLE = ManimColor("#910951") REDDYBROWN = ManimColor("#6E1005") REDORANGE = ManimColor("#FD3C06") REDPINK = ManimColor("#FA2A55") REDPURPLE = ManimColor("#820747") REDVIOLET = ManimColor("#9E0168") REDWINE = ManimColor("#8C0034") RICHBLUE = ManimColor("#021BF9") RICHPURPLE = ManimColor("#720058") ROBINEGGBLUE = ManimColor("#8AF1FE") ROBINSEGG = ManimColor("#6DEDFD") ROBINSEGGBLUE = ManimColor("#98EFF9") ROSA = ManimColor("#FE86A4") ROSE = ManimColor("#CF6275") ROSEPINK = ManimColor("#F7879A") ROSERED = ManimColor("#BE013C") ROSYPINK = ManimColor("#F6688E") ROGUE = ManimColor("#AB1239") ROYAL = ManimColor("#0C1793") ROYALBLUE = ManimColor("#0504AA") ROYALPURPLE = ManimColor("#4B006E") RUBY = ManimColor("#CA0147") RUSSET = ManimColor("#A13905") RUST = ManimColor("#A83C09") RUSTBROWN = ManimColor("#8B3103") RUSTORANGE = ManimColor("#C45508") RUSTRED = ManimColor("#AA2704") RUSTYORANGE = ManimColor("#CD5909") RUSTYRED = ManimColor("#AF2F0D") SAFFRON = ManimColor("#FEB209") SAGE = ManimColor("#87AE73") SAGEGREEN = ManimColor("#88B378") SALMON = ManimColor("#FF796C") SALMONPINK = ManimColor("#FE7B7C") SAND = ManimColor("#E2CA76") SANDBROWN = ManimColor("#CBA560") SANDSTONE = ManimColor("#C9AE74") SANDY = ManimColor("#F1DA7A") SANDYBROWN = ManimColor("#C4A661") SANDYELLOW = ManimColor("#FCE166") SANDYYELLOW = ManimColor("#FDEE73") SAPGREEN = ManimColor("#5C8B15") SAPPHIRE = ManimColor("#2138AB") SCARLET = ManimColor("#BE0119") SEA = ManimColor("#3C9992") SEABLUE = ManimColor("#047495") SEAFOAM = ManimColor("#80F9AD") SEAFOAMBLUE = ManimColor("#78D1B6") SEAFOAMGREEN = ManimColor("#7AF9AB") SEAGREEN = ManimColor("#53FCA1") SEAWEED = ManimColor("#18D17B") SEAWEEDGREEN = ManimColor("#35AD6B") SEPIA = ManimColor("#985E2B") SHAMROCK = ManimColor("#01B44C") SHAMROCKGREEN = ManimColor("#02C14D") SHIT = ManimColor("#7F5F00") SHITBROWN = ManimColor("#7B5804") SHITGREEN = ManimColor("#758000") SHOCKINGPINK = ManimColor("#FE02A2") SICKGREEN = ManimColor("#9DB92C") SICKLYGREEN = ManimColor("#94B21C") SICKLYYELLOW = ManimColor("#D0E429") SIENNA = ManimColor("#A9561E") SILVER = ManimColor("#C5C9C7") SKY = ManimColor("#82CAFC") SKYBLUE = ManimColor("#75BBFD") SLATE = ManimColor("#516572") SLATEBLUE = ManimColor("#5B7C99") SLATEGREEN = ManimColor("#658D6D") SLATEGREY = ManimColor("#59656D") SLIMEGREEN = ManimColor("#99CC04") SNOT = ManimColor("#ACBB0D") SNOTGREEN = ManimColor("#9DC100") SOFTBLUE = ManimColor("#6488EA") SOFTGREEN = ManimColor("#6FC276") SOFTPINK = ManimColor("#FDB0C0") SOFTPURPLE = ManimColor("#A66FB5") SPEARMINT = ManimColor("#1EF876") SPRINGGREEN = ManimColor("#A9F971") SPRUCE = ManimColor("#0A5F38") SQUASH = ManimColor("#F2AB15") STEEL = ManimColor("#738595") STEELBLUE = ManimColor("#5A7D9A") STEELGREY = ManimColor("#6F828A") STONE = ManimColor("#ADA587") STORMYBLUE = ManimColor("#507B9C") STRAW = ManimColor("#FCF679") STRAWBERRY = ManimColor("#FB2943") STRONGBLUE = ManimColor("#0C06F7") STRONGPINK = ManimColor("#FF0789") SUNFLOWER = ManimColor("#FFC512") SUNFLOWERYELLOW = ManimColor("#FFDA03") SUNNYYELLOW = ManimColor("#FFF917") SUNSHINEYELLOW = ManimColor("#FFFD37") SUNYELLOW = ManimColor("#FFDF22") SWAMP = ManimColor("#698339") SWAMPGREEN = ManimColor("#748500") TAN = ManimColor("#D1B26F") TANBROWN
|
ManimColor("#738595") STEELBLUE = ManimColor("#5A7D9A") STEELGREY = ManimColor("#6F828A") STONE = ManimColor("#ADA587") STORMYBLUE = ManimColor("#507B9C") STRAW = ManimColor("#FCF679") STRAWBERRY = ManimColor("#FB2943") STRONGBLUE = ManimColor("#0C06F7") STRONGPINK = ManimColor("#FF0789") SUNFLOWER = ManimColor("#FFC512") SUNFLOWERYELLOW = ManimColor("#FFDA03") SUNNYYELLOW = ManimColor("#FFF917") SUNSHINEYELLOW = ManimColor("#FFFD37") SUNYELLOW = ManimColor("#FFDF22") SWAMP = ManimColor("#698339") SWAMPGREEN = ManimColor("#748500") TAN = ManimColor("#D1B26F") TANBROWN = ManimColor("#AB7E4C") TANGERINE = ManimColor("#FF9408") TANGREEN = ManimColor("#A9BE70") TAUPE = ManimColor("#B9A281") TEA = ManimColor("#65AB7C") TEAGREEN = ManimColor("#BDF8A3") TEAL = ManimColor("#029386") TEALBLUE = ManimColor("#01889F") TEALGREEN = ManimColor("#25A36F") TEALISH = ManimColor("#24BCA8") TEALISHGREEN = ManimColor("#0CDC73") TERRACOTA = ManimColor("#CB6843") TERRACOTTA = ManimColor("#C9643B") TIFFANYBLUE = ManimColor("#7BF2DA") TOMATO = ManimColor("#EF4026") TOMATORED = ManimColor("#EC2D01") TOPAZ = ManimColor("#13BBAF") TOUPE = ManimColor("#C7AC7D") TOXICGREEN = ManimColor("#61DE2A") TREEGREEN = ManimColor("#2A7E19") TRUEBLUE = ManimColor("#010FCC") TRUEGREEN = ManimColor("#089404") TURQUOISE = ManimColor("#06C2AC") TURQUOISEBLUE = ManimColor("#06B1C4") TURQUOISEGREEN = ManimColor("#04F489") TURTLEGREEN = ManimColor("#75B84F") TWILIGHT = ManimColor("#4E518B") TWILIGHTBLUE = ManimColor("#0A437A") UGLYBLUE = ManimColor("#31668A") UGLYBROWN = ManimColor("#7D7103") UGLYGREEN = ManimColor("#7A9703") UGLYPINK = ManimColor("#CD7584") UGLYPURPLE = ManimColor("#A442A0") UGLYYELLOW = ManimColor("#D0C101") ULTRAMARINE = ManimColor("#2000B1") ULTRAMARINEBLUE = ManimColor("#1805DB") UMBER = ManimColor("#B26400") VELVET = ManimColor("#750851") VERMILION = ManimColor("#F4320C") VERYDARKBLUE = ManimColor("#000133") VERYDARKBROWN = ManimColor("#1D0200") VERYDARKGREEN = ManimColor("#062E03") VERYDARKPURPLE = ManimColor("#2A0134") VERYLIGHTBLUE = ManimColor("#D5FFFF") VERYLIGHTBROWN = ManimColor("#D3B683") VERYLIGHTGREEN = ManimColor("#D1FFBD") VERYLIGHTPINK = ManimColor("#FFF4F2") VERYLIGHTPURPLE = ManimColor("#F6CEFC") VERYPALEBLUE = ManimColor("#D6FFFE") VERYPALEGREEN = ManimColor("#CFFDBC") VIBRANTBLUE = ManimColor("#0339F8") VIBRANTGREEN = ManimColor("#0ADD08") VIBRANTPURPLE = ManimColor("#AD03DE") VIOLET = ManimColor("#9A0EEA") VIOLETBLUE = ManimColor("#510AC9") VIOLETPINK = ManimColor("#FB5FFC") VIOLETRED = ManimColor("#A50055") VIRIDIAN = ManimColor("#1E9167") VIVIDBLUE = ManimColor("#152EFF") VIVIDGREEN = ManimColor("#2FEF10") VIVIDPURPLE = ManimColor("#9900FA") VOMIT = ManimColor("#A2A415") VOMITGREEN = ManimColor("#89A203") VOMITYELLOW = ManimColor("#C7C10C") WARMBLUE = ManimColor("#4B57DB") WARMBROWN = ManimColor("#964E02") WARMGREY = ManimColor("#978A84") WARMPINK = ManimColor("#FB5581") WARMPURPLE = ManimColor("#952E8F") WASHEDOUTGREEN = ManimColor("#BCF5A6") WATERBLUE = ManimColor("#0E87CC") WATERMELON = ManimColor("#FD4659") WEIRDGREEN = ManimColor("#3AE57F") WHEAT = ManimColor("#FBDD7E") WHITE = ManimColor("#FFFFFF") WINDOWSBLUE = ManimColor("#3778BF") WINE = ManimColor("#80013F") WINERED = ManimColor("#7B0323") WINTERGREEN = ManimColor("#20F986") WISTERIA = ManimColor("#A87DC2") YELLOW = ManimColor("#FFFF14") YELLOWBROWN = ManimColor("#B79400") YELLOWGREEN = ManimColor("#BBF90F") YELLOWISH = ManimColor("#FAEE66") YELLOWISHBROWN = ManimColor("#9B7A01") YELLOWISHGREEN = ManimColor("#B0DD16") YELLOWISHORANGE = ManimColor("#FFAB0F") YELLOWISHTAN = ManimColor("#FCFC81") YELLOWOCHRE = ManimColor("#CB9D06") YELLOWORANGE = ManimColor("#FCB001") YELLOWTAN = ManimColor("#FFE36E") YELLOWYBROWN = ManimColor("#AE8B0C") YELLOWYGREEN = ManimColor("#BFF128") ================================================ FILE: manim/utils/docbuild/__init__.py ================================================ """Utilities for building the Manim documentation. For more information about the Manim documentation building, see: - :doc:`/contributing/development`, specifically the ``Documentation`` bullet point under :ref:`polishing-changes-and-submitting-a-pull-request` - :doc:`/contributing/docs` .. autosummary:: :toctree: ../reference autoaliasattr_directive autocolor_directive manim_directive module_parsing """ ================================================ FILE: manim/utils/docbuild/autoaliasattr_directive.py ================================================ """A directive for documenting type aliases and other module-level attributes.""" from __future__ import annotations from typing import TYPE_CHECKING from docutils import nodes from docutils.parsers.rst import Directive from docutils.statemachine import ViewList from manim.utils.docbuild.module_parsing import parse_module_attributes if TYPE_CHECKING: from sphinx.application import Sphinx __all__ = ["AliasAttrDocumenter"] ALIAS_DOCS_DICT, DATA_DICT, TYPEVAR_DICT = parse_module_attributes() ALIAS_LIST = [ alias_name for module_dict in ALIAS_DOCS_DICT.values() for category_dict in module_dict.values() for alias_name in category_dict ] def smart_replace(base: str, alias: str, substitution: str) -> str: """Auxiliary function for substituting type aliases into a base string, when there are overlaps between the aliases themselves. Parameters ---------- base The string in which the type aliases will be located and replaced. alias The substring to be substituted. substitution The string which will replace every occurrence of ``alias``. Returns ------- str The new string
|
aliases into a base string, when there are overlaps between the aliases themselves. Parameters ---------- base The string in which the type aliases will be located and replaced. alias The substring to be substituted. substitution The string which will replace every occurrence of ``alias``. Returns ------- str The new string after the alias substitution. """ occurrences = [] len_alias = len(alias) len_base = len(base) def condition(char: str) -> bool: return not char.isalnum() and char != "_" start = 0 i = 0 while True: i = base.find(alias, start) if i == -1: break if (i == 0 or condition(base[i - 1])) and ( i + len_alias == len_base or condition(base[i + len_alias]) ): occurrences.append(i) start = i + len_alias for o in occurrences[::-1]: base = base[:o] + substitution + base[o + len_alias :] return base def setup(app: Sphinx) -> None: app.add_directive("autoaliasattr", AliasAttrDocumenter) class AliasAttrDocumenter(Directive): """Directive which replaces Sphinx's Autosummary for module-level attributes: instead, it manually crafts a new "Type Aliases" section, where all the module-level attributes which are explicitly annotated as :class:`TypeAlias` are considered as such, for their use all around the Manim docs. These type aliases are separated from the "regular" module-level attributes, which get their traditional "Module Attributes" section autogenerated with Sphinx's Autosummary under "Type Aliases". See ``docs/source/_templates/autosummary/module.rst`` to watch this directive in action. See :func:`~.parse_module_attributes` for more information on how the modules are parsed to obtain the :class:`TypeAlias` information and separate it from the other attributes. """ objtype = "autoaliasattr" required_arguments = 1 has_content = True def run(self) -> list[nodes.Element]: module_name = self.arguments[0] # not present in the keys of the DICTs module_name = module_name.removeprefix("manim.") module_alias_dict = ALIAS_DOCS_DICT.get(module_name, None) module_attrs_list = DATA_DICT.get(module_name, None) module_typevars = TYPEVAR_DICT.get(module_name, None) content = nodes.container() # Add "Type Aliases" section if module_alias_dict is not None: module_alias_section = nodes.section(ids=[f"{module_name}.alias"]) content += module_alias_section # Use a rubric (title-like), just like in `module.rst` module_alias_section += nodes.rubric(text="Type Aliases") # category_name: str # category_dict: AliasCategoryDict = dict[str, AliasInfo] for category_name, category_dict in module_alias_dict.items(): category_section = nodes.section( ids=[category_name.lower().replace(" ", "_")] ) module_alias_section += category_section # category_name can be possibly "" for uncategorized aliases if category_name: category_section += nodes.title(text=category_name) category_alias_container = nodes.container() category_section += category_alias_container # alias_name: str # alias_info: AliasInfo = dict[str, str] # Contains "definition": str # Can possibly contain "doc": str for alias_name, alias_info in category_dict.items(): # Replace all occurrences of type aliases in the # definition for automatic cross-referencing! alias_def = alias_info["definition"] for A in ALIAS_LIST: alias_def = smart_replace(alias_def, A, f":class:`~.{A}`") # Using the `.. class::` directive is CRUCIAL, since # function/method parameters are always annotated via # classes - therefore Sphinx expects a class unparsed = ViewList( [ f".. class:: {alias_name}", "", " .. parsed-literal::", "", f" {alias_def}", "", ] ) if "doc" in alias_info: # Replace all occurrences of type aliases in # the docs for automatic cross-referencing! alias_doc = alias_info["doc"] for A in ALIAS_LIST: alias_doc = alias_doc.replace(f"`{A}`", f":class:`~.{A}`") # also hyperlink the TypeVars from that module if module_typevars is not None: for T in module_typevars: alias_doc = alias_doc.replace(f"`{T}`", f":class:`{T}`") # Add all
|
alias_info: # Replace all occurrences of type aliases in # the docs for automatic cross-referencing! alias_doc = alias_info["doc"] for A in ALIAS_LIST: alias_doc = alias_doc.replace(f"`{A}`", f":class:`~.{A}`") # also hyperlink the TypeVars from that module if module_typevars is not None: for T in module_typevars: alias_doc = alias_doc.replace(f"`{T}`", f":class:`{T}`") # Add all the lines with 4 spaces behind, to consider all the # documentation as a paragraph INSIDE the `.. class::` block doc_lines = alias_doc.split("\n") unparsed.extend(ViewList([f" {line}" for line in doc_lines])) # Parse the reST text into a fresh container # https://www.sphinx-doc.org/en/master/extdev/markupapi.html#parsing-directive-content-as-rest alias_container = nodes.container() self.state.nested_parse(unparsed, 0, alias_container) category_alias_container += alias_container # then add the module TypeVars section if module_typevars is not None: module_typevars_section = nodes.section(ids=[f"{module_name}.typevars"]) content += module_typevars_section # Use a rubric (title-like), just like in `module.rst` module_typevars_section += nodes.rubric(text="TypeVar's") # name: str # definition: TypeVarDict = dict[str, str] for name, definition in module_typevars.items(): # Using the `.. class::` directive is CRUCIAL, since # function/method parameters are always annotated via # classes - therefore Sphinx expects a class unparsed = ViewList( [ f".. class:: {name}", "", " .. parsed-literal::", "", f" {definition}", "", ] ) # Parse the reST text into a fresh container # https://www.sphinx-doc.org/en/master/extdev/markupapi.html#parsing-directive-content-as-rest typevar_container = nodes.container() self.state.nested_parse(unparsed, 0, typevar_container) module_typevars_section += typevar_container # Then, add the traditional "Module Attributes" section if module_attrs_list is not None: module_attrs_section = nodes.section(ids=[f"{module_name}.data"]) content += module_attrs_section # Use the same rubric (title-like) as in `module.rst` module_attrs_section += nodes.rubric(text="Module Attributes") # Let Sphinx Autosummary do its thing as always # Add all the attribute names with 4 spaces behind, so that # they're considered as INSIDE the `.. autosummary::` block unparsed = ViewList( [ ".. autosummary::", *(f" {attr}" for attr in module_attrs_list), ] ) # Parse the reST text into a fresh container # https://www.sphinx-doc.org/en/master/extdev/markupapi.html#parsing-directive-content-as-rest data_container = nodes.container() self.state.nested_parse(unparsed, 0, data_container) module_attrs_section += data_container return [content] ================================================ FILE: manim/utils/docbuild/autocolor_directive.py ================================================ """A directive for documenting colors in Manim.""" from __future__ import annotations import inspect from typing import TYPE_CHECKING from docutils import nodes from docutils.parsers.rst import Directive from manim import ManimColor if TYPE_CHECKING: from sphinx.application import Sphinx __all__ = ["ManimColorModuleDocumenter"] def setup(app: Sphinx) -> None: app.add_directive("automanimcolormodule", ManimColorModuleDocumenter) class ManimColorModuleDocumenter(Directive): objtype = "automanimcolormodule" required_arguments = 1 has_content = True def add_directive_header(self, sig: str) -> None: # TODO: The Directive class has no method named # add_directive_header. super().add_directive_header(sig) # type: ignore[misc] def run(self) -> list[nodes.Element]: module_name = self.arguments[0] try: import importlib module = importlib.import_module(module_name) except ImportError: return [ nodes.error( None, # type: ignore[arg-type] nodes.paragraph(text=f"Failed to import module '{module_name}'"), ) ] # Number of Colors displayed in one row num_color_cols = 2 table = nodes.table(align="center") tgroup = nodes.tgroup(cols=num_color_cols * 2) table += tgroup for _ in range(num_color_cols * 2): tgroup += nodes.colspec(colwidth=1) # Create header rows for the table thead = nodes.thead() header_row = nodes.row() for _ in range(num_color_cols): header_col1 = nodes.paragraph(text="Color Name") header_col2 = nodes.paragraph(text="RGB Hex Code") header_row += nodes.entry("", header_col1) header_row += nodes.entry("", header_col2) thead += header_row tgroup += thead color_elements = [] for member_name, member_obj in inspect.getmembers(module): if isinstance(member_obj, ManimColor): r, g, b = member_obj.to_rgb() luminance
|
thead = nodes.thead() header_row = nodes.row() for _ in range(num_color_cols): header_col1 = nodes.paragraph(text="Color Name") header_col2 = nodes.paragraph(text="RGB Hex Code") header_row += nodes.entry("", header_col1) header_row += nodes.entry("", header_col2) thead += header_row tgroup += thead color_elements = [] for member_name, member_obj in inspect.getmembers(module): if isinstance(member_obj, ManimColor): r, g, b = member_obj.to_rgb() luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b # Choose the font color based on the background luminance font_color = "black" if luminance > 0.5 else "white" color_elements.append((member_name, member_obj.to_hex(), font_color)) tbody = nodes.tbody() for base_i in range(0, len(color_elements), num_color_cols): row = nodes.row() for idx in range(base_i, base_i + num_color_cols): if idx < len(color_elements): member_name, hex_code, font_color = color_elements[idx] col1 = nodes.literal(text=member_name) col2 = nodes.raw( "", f'<div style="background-color:{hex_code};padding: 0.25rem 0;border-radius:8px;margin: 0.5rem 0.2rem"><code style="color:{font_color};">{hex_code}</code></div>', format="html", ) else: col1 = nodes.literal(text="") col2 = nodes.raw("", "", format="html") row += nodes.entry("", col1) row += nodes.entry("", col2) tbody += row tgroup += tbody return [table] ================================================ FILE: manim/utils/docbuild/manim_directive.py ================================================ r""" A directive for including Manim videos in a Sphinx document =========================================================== When rendering the HTML documentation, the ``.. manim::`` directive implemented here allows to include rendered videos. Its basic usage that allows processing **inline content** looks as follows:: .. manim:: MyScene class MyScene(Scene): def construct(self): ... It is required to pass the name of the class representing the scene to be rendered to the directive. As a second application, the directive can also be used to render scenes that are defined within doctests, for example:: .. manim:: DirectiveDoctestExample :ref_classes: Dot >>> from manim import Create, Dot, RED, Scene >>> dot = Dot(color=RED) >>> dot.color ManimColor('#FC6255') >>> class DirectiveDoctestExample(Scene): ... def construct(self): ... self.play(Create(dot)) Options ------- Options can be passed as follows:: .. manim:: <Class name> :<option name>: <value> The following configuration options are supported by the directive: hide_source If this flag is present without argument, the source code is not displayed above the rendered video. no_autoplay If this flag is present without argument, the video will not autoplay. quality : {'low', 'medium', 'high', 'fourk'} Controls render quality of the video, in analogy to the corresponding command line flags. save_as_gif If this flag is present without argument, the scene is rendered as a gif. save_last_frame If this flag is present without argument, an image representing the last frame of the scene will be rendered and displayed, instead of a video. ref_classes A list of classes, separated by spaces, that is rendered in a reference block after the source code. ref_functions A list of functions, separated by spaces, that is rendered in a reference block after the source code. ref_methods A list of methods, separated by spaces, that is rendered in a reference block after the source code. """ from __future__ import annotations import csv import itertools as it import re import shutil import sys import textwrap from pathlib import Path from timeit import timeit from typing import TYPE_CHECKING, Any, TypedDict import jinja2 from docutils import nodes from docutils.parsers.rst import Directive, directives from docutils.statemachine import StringList from manim import QUALITIES from manim import __version__
|
csv import itertools as it import re import shutil import sys import textwrap from pathlib import Path from timeit import timeit from typing import TYPE_CHECKING, Any, TypedDict import jinja2 from docutils import nodes from docutils.parsers.rst import Directive, directives from docutils.statemachine import StringList from manim import QUALITIES from manim import __version__ as manim_version if TYPE_CHECKING: from sphinx.application import Sphinx __all__ = ["ManimDirective"] classnamedict: dict[str, int] = {} class SetupMetadata(TypedDict): parallel_read_safe: bool parallel_write_safe: bool class SkipManimNode(nodes.Admonition, nodes.Element): """Auxiliary node class that is used when the ``skip-manim`` tag is present or ``.pot`` files are being built. Skips rendering the manim directive and outputs a placeholder instead. """ pass def visit(self: SkipManimNode, node: nodes.Element, name: str = "") -> None: # TODO: Parent classes don't have a visit_admonition() method. self.visit_admonition(node, name) # type: ignore[attr-defined] if not isinstance(node[0], nodes.title): node.insert(0, nodes.title("skip-manim", "Example Placeholder")) def depart(self: SkipManimNode, node: nodes.Element) -> None: # TODO: Parent classes don't have a depart_admonition() method. self.depart_admonition(node) # type: ignore[attr-defined] def process_name_list(option_input: str, reference_type: str) -> list[str]: r"""Reformats a string of space separated class names as a list of strings containing valid Sphinx references. Tests ----- :: >>> process_name_list("Tex TexTemplate", "class") [':class:`~.Tex`', ':class:`~.TexTemplate`'] >>> process_name_list("Scene.play Mobject.rotate", "func") [':func:`~.Scene.play`', ':func:`~.Mobject.rotate`'] """ return [f":{reference_type}:`~.{name}`" for name in option_input.split()] class ManimDirective(Directive): r"""The manim directive, rendering videos while building the documentation. See the module docstring for documentation. """ has_content = True required_arguments = 1 optional_arguments = 0 option_spec = { "hide_source": bool, "no_autoplay": bool, "quality": lambda arg: directives.choice( arg, ("low", "medium", "high", "fourk"), ), "save_as_gif": bool, "save_last_frame": bool, "ref_modules": lambda arg: process_name_list(arg, "mod"), "ref_classes": lambda arg: process_name_list(arg, "class"), "ref_functions": lambda arg: process_name_list(arg, "func"), "ref_methods": lambda arg: process_name_list(arg, "meth"), } final_argument_whitespace = True def run(self) -> list[nodes.Element]: # Rendering is skipped if the tag skip-manim is present, # or if we are making the pot-files should_skip = ( "skip-manim" in self.state.document.settings.env.app.builder.tags or self.state.document.settings.env.app.builder.name == "gettext" ) if should_skip: clsname = self.arguments[0] node = SkipManimNode() self.state.nested_parse( StringList( [ f"Placeholder block for ``{clsname}``.", "", ".. code-block:: python", "", ] + [" " + line for line in self.content] + [ "", ".. raw:: html", "", f' <pre data-manim-binder data-manim-classname="{clsname}">', ] + [" " + line for line in self.content] + [" </pre>"], ), self.content_offset, node, ) return [node] from manim import config, tempconfig global classnamedict clsname = self.arguments[0] if clsname not in classnamedict: classnamedict[clsname] = 1 else: classnamedict[clsname] += 1 hide_source = "hide_source" in self.options no_autoplay = "no_autoplay" in self.options save_as_gif = "save_as_gif" in self.options save_last_frame = "save_last_frame" in self.options assert not (save_as_gif and save_last_frame) ref_content = ( self.options.get("ref_modules", []) + self.options.get("ref_classes", []) + self.options.get("ref_functions", []) + self.options.get("ref_methods", []) ) ref_block = "References: " + " ".join(ref_content) if ref_content else "" if "quality" in self.options: quality = f"{self.options['quality']}_quality" else: quality = "example_quality" frame_rate = QUALITIES[quality]["frame_rate"] pixel_height = QUALITIES[quality]["pixel_height"] pixel_width = QUALITIES[quality]["pixel_width"] state_machine = self.state_machine document = state_machine.document source_file_name = Path(document.attributes["source"]) source_rel_name = source_file_name.relative_to(setup.confdir) # type: ignore[attr-defined] source_rel_dir = source_rel_name.parents[0] dest_dir = Path(setup.app.builder.outdir, source_rel_dir).absolute() # type: ignore[attr-defined] if not dest_dir.exists(): dest_dir.mkdir(parents=True, exist_ok=True) source_block_in = [ ".. code-block:: python", "", "
|
quality = "example_quality" frame_rate = QUALITIES[quality]["frame_rate"] pixel_height = QUALITIES[quality]["pixel_height"] pixel_width = QUALITIES[quality]["pixel_width"] state_machine = self.state_machine document = state_machine.document source_file_name = Path(document.attributes["source"]) source_rel_name = source_file_name.relative_to(setup.confdir) # type: ignore[attr-defined] source_rel_dir = source_rel_name.parents[0] dest_dir = Path(setup.app.builder.outdir, source_rel_dir).absolute() # type: ignore[attr-defined] if not dest_dir.exists(): dest_dir.mkdir(parents=True, exist_ok=True) source_block_in = [ ".. code-block:: python", "", " from manim import *\n", *(" " + line for line in self.content), "", ".. raw:: html", "", f' <pre data-manim-binder data-manim-classname="{clsname}">', *(" " + line for line in self.content), "", " </pre>", ] source_block = "\n".join(source_block_in) config.media_dir = (Path(setup.confdir) / "media").absolute() # type: ignore[attr-defined] config.images_dir = "{media_dir}/images" config.video_dir = "{media_dir}/videos/{quality}" output_file = f"{clsname}-{classnamedict[clsname]}" config.assets_dir = Path("_static") config.progress_bar = "none" config.verbosity = "WARNING" example_config = { "frame_rate": frame_rate, "no_autoplay": no_autoplay, "pixel_height": pixel_height, "pixel_width": pixel_width, "save_last_frame": save_last_frame, "write_to_movie": not save_last_frame, "output_file": output_file, } if save_last_frame: example_config["format"] = None if save_as_gif: example_config["format"] = "gif" user_code = list(self.content) if user_code[0].startswith(">>> "): # check whether block comes from doctest user_code = [ line[4:] for line in user_code if line.startswith((">>> ", "... ")) ] code = [ "from manim import *", *user_code, f"{clsname}().render()", ] try: with tempconfig(example_config): run_time = timeit(lambda: exec("\n".join(code), globals()), number=1) video_dir = config.get_dir("video_dir") images_dir = config.get_dir("images_dir") except Exception as e: raise RuntimeError(f"Error while rendering example {clsname}") from e _write_rendering_stats( clsname, run_time, self.state.document.settings.env.docname, ) # copy video file to output directory if not (save_as_gif or save_last_frame): filename = f"{output_file}.mp4" filesrc = video_dir / filename destfile = Path(dest_dir, filename) shutil.copyfile(filesrc, destfile) elif save_as_gif: filename = f"{output_file}.gif" filesrc = video_dir / filename elif save_last_frame: filename = f"{output_file}.png" filesrc = images_dir / filename else: raise ValueError("Invalid combination of render flags received.") rendered_template = jinja2.Template(TEMPLATE).render( clsname=clsname, clsname_lowercase=clsname.lower(), hide_source=hide_source, filesrc_rel=Path(filesrc).relative_to(setup.confdir).as_posix(), # type: ignore[attr-defined] no_autoplay=no_autoplay, output_file=output_file, save_last_frame=save_last_frame, save_as_gif=save_as_gif, source_block=source_block, ref_block=ref_block, ) state_machine.insert_input( rendered_template.split("\n"), source=document.attributes["source"], ) return [] rendering_times_file_path = Path("../rendering_times.csv") def _write_rendering_stats(scene_name: str, run_time: float, file_name: str) -> None: with rendering_times_file_path.open("a") as file: csv.writer(file).writerow( [ re.sub(r"^(reference\/)|(manim\.)", "", file_name), scene_name, f"{run_time:.3f}", ], ) def _log_rendering_times(*args: tuple[Any]) -> None: if rendering_times_file_path.exists(): with rendering_times_file_path.open() as file: data = list(csv.reader(file)) if len(data) == 0: sys.exit() print("\nRendering Summary\n-----------------\n") # filter out empty lists caused by csv reader data = [row for row in data if row] max_file_length = max(len(row[0]) for row in data) for key, group_iter in it.groupby(data, key=lambda row: row[0]): key = key.ljust(max_file_length + 1, ".") group = list(group_iter) if len(group) == 1: row = group[0] print(f"{key}{row[2].rjust(7, '.')}s {row[1]}") continue time_sum = sum(float(row[2]) for row in group) print( f"{key}{f'{time_sum:.3f}'.rjust(7, '.')}s => {len(group)} EXAMPLES", ) for row in group: print(f"{' ' * max_file_length} {row[2].rjust(7)}s {row[1]}") print("") def _delete_rendering_times(*args: tuple[Any]) -> None: if rendering_times_file_path.exists(): rendering_times_file_path.unlink() def setup(app: Sphinx) -> SetupMetadata: app.add_node( SkipManimNode, html=(visit, depart), latex=(lambda a, b: None, lambda a, b: None), ) setup.app = app # type: ignore[attr-defined] setup.config = app.config # type: ignore[attr-defined] setup.confdir = app.confdir # type: ignore[attr-defined] app.add_directive("manim", ManimDirective) app.connect("builder-inited", _delete_rendering_times) app.connect("build-finished", _log_rendering_times) app.add_js_file("manim-binder.min.js") app.add_js_file( None, body=textwrap.dedent( f"""\ window.initManimBinder({{branch: "v{manim_version}"}}) """ ).strip(), ) metadata: SetupMetadata = { "parallel_read_safe": False, "parallel_write_safe": True, } return metadata TEMPLATE = r""" {% if not hide_source %} .. raw:: html <div id="{{ clsname_lowercase }}" class="admonition admonition-manim-example"> <p
|
= app.confdir # type: ignore[attr-defined] app.add_directive("manim", ManimDirective) app.connect("builder-inited", _delete_rendering_times) app.connect("build-finished", _log_rendering_times) app.add_js_file("manim-binder.min.js") app.add_js_file( None, body=textwrap.dedent( f"""\ window.initManimBinder({{branch: "v{manim_version}"}}) """ ).strip(), ) metadata: SetupMetadata = { "parallel_read_safe": False, "parallel_write_safe": True, } return metadata TEMPLATE = r""" {% if not hide_source %} .. raw:: html <div id="{{ clsname_lowercase }}" class="admonition admonition-manim-example"> <p class="admonition-title">Example: {{ clsname }} <a class="headerlink" href="#{{ clsname_lowercase }}">¶</a></p> {% endif %} {% if not (save_as_gif or save_last_frame) %} .. raw:: html <video class="manim-video" controls loop {{ '' if no_autoplay else 'autoplay' }} src="./{{ output_file }}.mp4"> </video> {% elif save_as_gif %} .. image:: /{{ filesrc_rel }} :align: center {% elif save_last_frame %} .. image:: /{{ filesrc_rel } :align: center {% endif %} {% if not hide_source %} {{ source_block }} {{ ref_block }} .. raw:: html </div> {% endif %} """ ================================================ FILE: manim/utils/docbuild/module_parsing.py ================================================ """Read and parse all the Manim modules and extract documentation from them.""" from __future__ import annotations import ast import sys from ast import Attribute, Name, Subscript from pathlib import Path from typing import Any from typing_extensions import TypeAlias __all__ = ["parse_module_attributes"] AliasInfo: TypeAlias = dict[str, str] """Dictionary with a `definition` key containing the definition of a :class:`TypeAlias` as a string, and optionally a `doc` key containing the documentation for that alias, if it exists. """ AliasCategoryDict: TypeAlias = dict[str, AliasInfo] """Dictionary which holds an `AliasInfo` for every alias name in a same category. """ ModuleLevelAliasDict: TypeAlias = dict[str, AliasCategoryDict] """Dictionary containing every :class:`TypeAlias` defined in a module, classified by category in different `AliasCategoryDict` objects. """ ModuleTypeVarDict: TypeAlias = dict[str, str] """Dictionary containing every :class:`TypeVar` defined in a module.""" AliasDocsDict: TypeAlias = dict[str, ModuleLevelAliasDict] """Dictionary which, for every module in Manim, contains documentation about their module-level attributes which are explicitly defined as :class:`TypeAlias`, separating them from the rest of attributes. """ DataDict: TypeAlias = dict[str, list[str]] """Type for a dictionary which, for every module, contains a list with the names of all their DOCUMENTED module-level attributes (identified by Sphinx via the ``data`` role, hence the name) which are NOT explicitly defined as :class:`TypeAlias`. """ TypeVarDict: TypeAlias = dict[str, ModuleTypeVarDict] """A dictionary mapping module names to dictionaries of :class:`TypeVar` objects.""" ALIAS_DOCS_DICT: AliasDocsDict = {} DATA_DICT: DataDict = {} TYPEVAR_DICT: TypeVarDict = {} MANIM_ROOT = Path(__file__).resolve().parent.parent.parent # In the following, we will use ``type(xyz) is xyz_type`` instead of # isinstance checks to make sure no subclasses of the type pass the # check # ruff: noqa: E721 def parse_module_attributes() -> tuple[AliasDocsDict, DataDict, TypeVarDict]: """Read all files, generate Abstract Syntax Trees from them, and extract useful information about the type aliases defined in the files: the category they belong to, their definition and their description, separating them from the "regular" module attributes. Returns ------- ALIAS_DOCS_DICT : :class:`AliasDocsDict` A dictionary containing the information from all the type aliases in Manim. See :class:`AliasDocsDict` for more information. DATA_DICT : :class:`DataDict` A dictionary containing the names of all DOCUMENTED module-level attributes which are not a :class:`TypeAlias`. TYPEVAR_DICT : :class:`TypeVarDict` A dictionary containing the definitions of :class:`TypeVar` objects, organized by modules. """ global ALIAS_DOCS_DICT
|
containing the information from all the type aliases in Manim. See :class:`AliasDocsDict` for more information. DATA_DICT : :class:`DataDict` A dictionary containing the names of all DOCUMENTED module-level attributes which are not a :class:`TypeAlias`. TYPEVAR_DICT : :class:`TypeVarDict` A dictionary containing the definitions of :class:`TypeVar` objects, organized by modules. """ global ALIAS_DOCS_DICT global DATA_DICT global TYPEVAR_DICT if ALIAS_DOCS_DICT or DATA_DICT or TYPEVAR_DICT: return ALIAS_DOCS_DICT, DATA_DICT, TYPEVAR_DICT for module_path in MANIM_ROOT.rglob("*.py"): module_name_t1 = module_path.resolve().relative_to(MANIM_ROOT) module_name_t2 = list(module_name_t1.parts) module_name_t2[-1] = module_name_t2[-1].removesuffix(".py") module_name = ".".join(module_name_t2) module_content = module_path.read_text(encoding="utf-8") # For storing TypeAliases module_dict: ModuleLevelAliasDict = {} category_dict: AliasCategoryDict | None = None alias_info: AliasInfo | None = None # For storing TypeVars module_typevars: ModuleTypeVarDict = {} # For storing regular module attributes data_list: list[str] = [] data_name: str | None = None for node in ast.iter_child_nodes(ast.parse(module_content)): # If we encounter a string: if ( type(node) is ast.Expr and type(node.value) is ast.Constant and type(node.value.value) is str ): string = node.value.value.strip() # It can be the start of a category section_str = "[CATEGORY]" if string.startswith(section_str): category_name = string[len(section_str) :].strip() module_dict[category_name] = {} category_dict = module_dict[category_name] alias_info = None # or a docstring of the alias defined before elif alias_info: alias_info["doc"] = string # or a docstring of the module attribute defined before elif data_name: data_list.append(data_name) continue # if it's defined under if TYPE_CHECKING # go through the body of the if statement if ( # NOTE: This logic does not (and cannot) # check if the comparison is against a # variable called TYPE_CHECKING # It also says that you cannot do the following # import typing as foo # if foo.TYPE_CHECKING: # BAR: TypeAlias = ... type(node) is ast.If and ( ( # if TYPE_CHECKING type(node.test) is ast.Name and node.test.id == "TYPE_CHECKING" ) or ( # if typing.TYPE_CHECKING type(node.test) is ast.Attribute and type(node.test.value) is ast.Name and node.test.value.id == "typing" and node.test.attr == "TYPE_CHECKING" ) ) ): inner_nodes: list[Any] = node.body else: inner_nodes = [node] for node in inner_nodes: # Check if this node is a TypeAlias (type <name> = <value>) # or an AnnAssign annotated as TypeAlias (<target>: TypeAlias = <value>). is_type_alias = ( sys.version_info >= (3, 12) and type(node) is ast.TypeAlias ) is_annotated_assignment_with_value = ( type(node) is ast.AnnAssign and type(node.annotation) is ast.Name and node.annotation.id == "TypeAlias" and type(node.target) is ast.Name and node.value is not None ) if is_type_alias or is_annotated_assignment_with_value: # TODO: ast.TypeAlias does not exist before Python 3.12, and that # could be the reason why MyPy does not recognize these as # attributes of node. alias_name = node.name.id if is_type_alias else node.target.id definition_node = node.value # If the definition is a Union, replace with vertical bar notation. # Instead of "Union[Type1, Type2]", we'll have "Type1 | Type2". if ( type(definition_node) is ast.Subscript and type(definition_node.value) is ast.Name and definition_node.value.id == "Union" ): union_elements = definition_node.slice.elts # type: ignore[attr-defined] definition = " | ".join( ast.unparse(elem) for elem in union_elements ) else: definition = ast.unparse(definition_node) definition = definition.replace("npt.", "") if category_dict is None: module_dict[""] = {} category_dict = module_dict[""] category_dict[alias_name] = {"definition": definition} alias_info = category_dict[alias_name]
|
type(definition_node.value) is ast.Name and definition_node.value.id == "Union" ): union_elements = definition_node.slice.elts # type: ignore[attr-defined] definition = " | ".join( ast.unparse(elem) for elem in union_elements ) else: definition = ast.unparse(definition_node) definition = definition.replace("npt.", "") if category_dict is None: module_dict[""] = {} category_dict = module_dict[""] category_dict[alias_name] = {"definition": definition} alias_info = category_dict[alias_name] continue # Check if it is a typing.TypeVar (<target> = TypeVar(...)). elif ( type(node) is ast.Assign and type(node.targets[0]) is ast.Name and type(node.value) is ast.Call and type(node.value.func) is ast.Name and node.value.func.id.endswith("TypeVar") ): module_typevars[node.targets[0].id] = ast.unparse( node.value ).replace("_", r"\_") continue # If here, the node is not a TypeAlias definition alias_info = None # It could still be a module attribute definition. # Does the assignment have a target of type Name? Then # it could be considered a definition of a module attribute. if type(node) is ast.AnnAssign: target: Name | Attribute | Subscript | ast.expr | None = node.target elif type(node) is ast.Assign and len(node.targets) == 1: target = node.targets[0] else: target = None if type(target) is ast.Name and not ( type(node) is ast.Assign and target.id not in module_typevars ): data_name = target.id else: data_name = None if len(module_dict) > 0: ALIAS_DOCS_DICT[module_name] = module_dict if len(data_list) > 0: DATA_DICT[module_name] = data_list if module_typevars: TYPEVAR_DICT[module_name] = module_typevars return ALIAS_DOCS_DICT, DATA_DICT, TYPEVAR_DICT ================================================ FILE: manim/utils/testing/__init__.py ================================================ """Utilities for Manim tests using `pytest <https://pytest.org>`_. For more information about Manim testing, see: - :doc:`/contributing/development`, specifically the ``Tests`` bullet point under :ref:`polishing-changes-and-submitting-a-pull-request` - :doc:`/contributing/testing` .. autosummary:: :toctree: ../reference frames_comparison _frames_testers _show_diff _test_class_makers """ ================================================ FILE: manim/utils/testing/_frames_testers.py ================================================ from __future__ import annotations import contextlib import logging import warnings from collections.abc import Generator from pathlib import Path import numpy as np from manim.typing import PixelArray from ._show_diff import show_diff_helper FRAME_ABSOLUTE_TOLERANCE = 1.01 FRAME_MISMATCH_RATIO_TOLERANCE = 1e-5 logger = logging.getLogger("manim") class _FramesTester: def __init__(self, file_path: Path, show_diff: bool = False) -> None: self._file_path = file_path self._show_diff = show_diff self._frames: np.ndarray self._number_frames: int = 0 self._frames_compared = 0 @contextlib.contextmanager def testing(self) -> Generator[None, None, None]: with np.load(self._file_path) as data: self._frames = data["frame_data"] # For backward compatibility, when the control data contains only one frame (<= v0.8.0) if len(self._frames.shape) != 4: self._frames = np.expand_dims(self._frames, axis=0) logger.debug(self._frames.shape) self._number_frames = np.ma.size(self._frames, axis=0) yield assert self._frames_compared == self._number_frames, ( f"The scene tested contained {self._frames_compared} frames, " f"when there are {self._number_frames} control frames for this test." ) def check_frame(self, frame_number: int, frame: PixelArray) -> None: assert frame_number < self._number_frames, ( f"The tested scene is at frame number {frame_number} " f"when there are {self._number_frames} control frames." ) try: np.testing.assert_allclose( frame, self._frames[frame_number], atol=FRAME_ABSOLUTE_TOLERANCE, err_msg=f"Frame no {frame_number}. You can use --show_diff to visually show the difference.", verbose=False, ) self._frames_compared += 1 except AssertionError as e: number_of_matches = np.isclose( frame, self._frames[frame_number], atol=FRAME_ABSOLUTE_TOLERANCE ).sum() number_of_mismatches = frame.size - number_of_matches if number_of_mismatches / frame.size < FRAME_MISMATCH_RATIO_TOLERANCE: # we tolerate a small (< 0.001%) amount of pixel value errors # in the tests, this accounts for minor OS dependent inconsistencies self._frames_compared += 1 warnings.warn( f"Mismatch of {number_of_mismatches} pixel values in frame {frame_number} " f"against control data in {self._file_path}. Below error threshold, " "continuing...",
|
/ frame.size < FRAME_MISMATCH_RATIO_TOLERANCE: # we tolerate a small (< 0.001%) amount of pixel value errors # in the tests, this accounts for minor OS dependent inconsistencies self._frames_compared += 1 warnings.warn( f"Mismatch of {number_of_mismatches} pixel values in frame {frame_number} " f"against control data in {self._file_path}. Below error threshold, " "continuing...", stacklevel=1, ) return if self._show_diff: show_diff_helper( frame_number, frame, self._frames[frame_number], self._file_path.name, ) raise e class _ControlDataWriter(_FramesTester): def __init__(self, file_path: Path, size_frame: tuple) -> None: self.file_path = file_path self.frames = np.empty((0, *size_frame, 4)) self._number_frames_written: int = 0 # Actually write a frame. def check_frame(self, index: int, frame: PixelArray) -> None: frame = frame[np.newaxis, ...] self.frames = np.concatenate((self.frames, frame)) self._number_frames_written += 1 @contextlib.contextmanager def testing(self) -> Generator[None, None, None]: yield self.save_contol_data() def save_contol_data(self) -> None: self.frames = self.frames.astype("uint8") np.savez_compressed(self.file_path, frame_data=self.frames) logger.info( f"{self._number_frames_written} control frames saved in {self.file_path}", ) ================================================ FILE: manim/utils/testing/_show_diff.py ================================================ from __future__ import annotations import logging import warnings import numpy as np from manim.typing import PixelArray def show_diff_helper( frame_number: int, frame_data: PixelArray, expected_frame_data: PixelArray, control_data_filename: str, ) -> None: """Will visually display with matplotlib differences between frame generated and the one expected.""" import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt gs = gridspec.GridSpec(2, 2) fig = plt.figure() fig.suptitle(f"Test difference summary at frame {frame_number}", fontsize=16) ax = fig.add_subplot(gs[0, 0]) ax.imshow(frame_data) ax.set_title("Generated") ax = fig.add_subplot(gs[0, 1]) ax.imshow(expected_frame_data) ax.set_title("Expected") ax = fig.add_subplot(gs[1, :]) diff_im = expected_frame_data.copy() diff_im = np.where( frame_data != np.array([0, 0, 0, 255]), np.array([0, 255, 0, 255], dtype="uint8"), np.array([0, 0, 0, 255], dtype="uint8"), ) # Set any non-black pixels to green np.putmask( diff_im, expected_frame_data != frame_data, np.array([255, 0, 0, 255], dtype="uint8"), ) # Set any different pixels to red ax.imshow(diff_im, interpolation="nearest") ax.set_title("Difference summary: (green = same, red = different)") with warnings.catch_warnings(): warnings.simplefilter("error") try: plt.show() except UserWarning: filename = f"{control_data_filename[:-4]}-diff.pdf" plt.savefig(filename) logging.warning( "Interactive matplotlib interface not available," f" diff saved to {filename}." ) ================================================ FILE: manim/utils/testing/_test_class_makers.py ================================================ from __future__ import annotations from collections.abc import Callable from typing import Any from manim.renderer.cairo_renderer import CairoRenderer from manim.renderer.opengl_renderer import OpenGLRenderer from manim.scene.scene import Scene from manim.scene.scene_file_writer import SceneFileWriter from manim.typing import PixelArray, StrPath from ._frames_testers import _FramesTester def _make_test_scene_class( base_scene: type[Scene], construct_test: Callable[[Scene], None], test_renderer: CairoRenderer | OpenGLRenderer | None, ) -> type[Scene]: # TODO: Get the type annotation right for the base_scene argument. class _TestedScene(base_scene): # type: ignore[valid-type, misc] def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, renderer=test_renderer, **kwargs) def construct(self) -> None: construct_test(self) # Manim hack to render the very last frame (normally the last frame is not the very end of the animation) if self.animations is not None: self.update_to_time(self.get_run_time(self.animations)) self.renderer.render(self, 1, self.moving_mobjects) return _TestedScene def _make_test_renderer_class(from_renderer: type) -> Any: # Just for inheritance. class _TestRenderer(from_renderer): pass return _TestRenderer class DummySceneFileWriter(SceneFileWriter): """Delegate of SceneFileWriter used to test the frames.""" def __init__( self, renderer: CairoRenderer | OpenGLRenderer, scene_name: str, **kwargs: Any, ) -> None: super().__init__(renderer, scene_name, **kwargs) self.i = 0 def init_output_directories(self, scene_name: str) -> None: pass def add_partial_movie_file(self, hash_animation: str | None) -> None: pass def begin_animation( self, allow_write: bool = True, file_path: StrPath | None = None ) -> Any: pass def
|
CairoRenderer | OpenGLRenderer, scene_name: str, **kwargs: Any, ) -> None: super().__init__(renderer, scene_name, **kwargs) self.i = 0 def init_output_directories(self, scene_name: str) -> None: pass def add_partial_movie_file(self, hash_animation: str | None) -> None: pass def begin_animation( self, allow_write: bool = True, file_path: StrPath | None = None ) -> Any: pass def end_animation(self, allow_write: bool = False) -> None: pass def combine_to_movie(self) -> None: pass def combine_to_section_videos(self) -> None: pass def clean_cache(self) -> None: pass def write_frame( self, frame_or_renderer: PixelArray | OpenGLRenderer, num_frames: int = 1 ) -> None: self.i += 1 def _make_scene_file_writer_class(tester: _FramesTester) -> type[SceneFileWriter]: class TestSceneFileWriter(DummySceneFileWriter): def write_frame( self, frame_or_renderer: PixelArray | OpenGLRenderer, num_frames: int = 1 ) -> None: tester.check_frame(self.i, frame_or_renderer) super().write_frame(frame_or_renderer, num_frames=num_frames) return TestSceneFileWriter ================================================ FILE: manim/utils/testing/config_graphical_tests_monoframe.cfg ================================================ # Custom manim configuration used to run tests when only using the last frame. [CLI] frame_rate = 6 pixel_height = 480 pixel_width = 854 disable_caching = True ================================================ FILE: manim/utils/testing/config_graphical_tests_multiframes.cfg ================================================ # Custom manim configuration used to run tests when testing several frames. [CLI] frame_rate = 6 pixel_height = 240 pixel_width = 427 disable_caching = True ================================================ FILE: manim/utils/testing/frames_comparison.py ================================================ from __future__ import annotations import functools import inspect from collections.abc import Callable from pathlib import Path from typing import Any import cairo import pytest from _pytest.fixtures import FixtureRequest from manim import Scene from manim._config import tempconfig from manim._config.utils import ManimConfig from manim.camera.three_d_camera import ThreeDCamera from manim.renderer.cairo_renderer import CairoRenderer from manim.renderer.opengl_renderer import OpenGLRenderer from manim.scene.three_d_scene import ThreeDScene from manim.typing import StrPath from ._frames_testers import _ControlDataWriter, _FramesTester from ._test_class_makers import ( DummySceneFileWriter, _make_scene_file_writer_class, _make_test_renderer_class, _make_test_scene_class, ) SCENE_PARAMETER_NAME = "scene" _tests_root_dir_path = Path(__file__).absolute().parents[2] PATH_CONTROL_DATA = _tests_root_dir_path / Path("control_data", "graphical_units_data") MIN_CAIRO_VERSION = 11800 def frames_comparison( func: Callable | None = None, *, last_frame: bool = True, renderer_class: type[CairoRenderer | OpenGLRenderer] = CairoRenderer, base_scene: type[Scene] = Scene, **custom_config: Any, ) -> Callable: """Compares the frames generated by the test with control frames previously registered. If there is no control frames for this test, the test will fail. To generate control frames for a given test, pass ``--set_test`` flag to pytest while running the test. Note that this decorator can be use with or without parentheses. Parameters ---------- last_frame whether the test should test the last frame, by default True. renderer_class The base renderer to use (OpenGLRenderer/CairoRenderer), by default CairoRenderer base_scene The base class for the scene (ThreeDScene, etc.), by default Scene .. warning:: By default, last_frame is True, which means that only the last frame is tested. If the scene has a moving animation, then the test must set last_frame to False. """ def decorator_maker(tested_scene_construct: Callable) -> Callable: if ( SCENE_PARAMETER_NAME not in inspect.getfullargspec(tested_scene_construct).args ): raise Exception( f"Invalid graphical test function test function : must have '{SCENE_PARAMETER_NAME}'as one of the parameters.", ) # Exclude "scene" from the argument list of the signature. old_sig = inspect.signature( functools.partial(tested_scene_construct, scene=None), ) if "__module_test__" not in tested_scene_construct.__globals__: raise Exception( "There is no module test name indicated for the graphical unit test. You have to declare __module_test__ in the test file.", ) module_name = tested_scene_construct.__globals__.get("__module_test__") assert isinstance(module_name, str) test_name
|
"scene" from the argument list of the signature. old_sig = inspect.signature( functools.partial(tested_scene_construct, scene=None), ) if "__module_test__" not in tested_scene_construct.__globals__: raise Exception( "There is no module test name indicated for the graphical unit test. You have to declare __module_test__ in the test file.", ) module_name = tested_scene_construct.__globals__.get("__module_test__") assert isinstance(module_name, str) test_name = tested_scene_construct.__name__[len("test_") :] @functools.wraps(tested_scene_construct) # The "request" parameter is meant to be used as a fixture by pytest. See below. def wrapper( *args: Any, request: FixtureRequest, tmp_path: StrPath, **kwargs: Any ) -> None: # check for cairo version if ( renderer_class is CairoRenderer and cairo.cairo_version() < MIN_CAIRO_VERSION ): pytest.skip("Cairo version is too old. Skipping cairo graphical tests.") # Wraps the test_function to a construct method, to "freeze" the eventual additional arguments (parametrizations fixtures). construct = functools.partial(tested_scene_construct, *args, **kwargs) # Kwargs contains the eventual parametrization arguments. # This modifies the test_name so that it is defined by the parametrization # arguments too. # Example: if "length" is parametrized from 0 to 20, the kwargs # will be once with {"length" : 1}, etc. test_name_with_param = test_name + "_".join( f"_{str(tup[0])}[{str(tup[1])}]" for tup in kwargs.items() ) config_tests = _config_test(last_frame) config_tests["text_dir"] = tmp_path config_tests["tex_dir"] = tmp_path if last_frame: config_tests["frame_rate"] = 1 config_tests["dry_run"] = True setting_test = request.config.getoption("--set_test") try: test_file_path = tested_scene_construct.__globals__["__file__"] except Exception: test_file_path = None real_test = _make_test_comparing_frames( file_path=_control_data_path( test_file_path, module_name, test_name_with_param, setting_test, ), base_scene=base_scene, construct=construct, renderer_class=renderer_class, is_set_test_data_test=setting_test, last_frame=last_frame, show_diff=request.config.getoption("--show_diff"), size_frame=(config_tests["pixel_height"], config_tests["pixel_width"]), ) # Isolate the config used for the test, to avoid modifying the global config during the test run. with tempconfig({**config_tests, **custom_config}): real_test() parameters = list(old_sig.parameters.values()) # Adds "request" param into the signature of the wrapper, to use the associated pytest fixture. # This fixture is needed to have access to flags value and pytest's config. See above. if "request" not in old_sig.parameters: parameters += [inspect.Parameter("request", inspect.Parameter.KEYWORD_ONLY)] if "tmp_path" not in old_sig.parameters: parameters += [ inspect.Parameter("tmp_path", inspect.Parameter.KEYWORD_ONLY), ] new_sig = old_sig.replace(parameters=parameters) wrapper.__signature__ = new_sig # type: ignore[attr-defined] # Reach a bit into pytest internals to hoist the marks from our wrapped # function. wrapper.pytestmark = [] # type: ignore[attr-defined] new_marks = getattr(tested_scene_construct, "pytestmark", []) wrapper.pytestmark = new_marks # type: ignore[attr-defined] return wrapper # Case where the decorator is called with and without parentheses. # If func is None, callabl(None) returns False if callable(func): return decorator_maker(func) return decorator_maker def _make_test_comparing_frames( file_path: Path, base_scene: type[Scene], construct: Callable[[Scene], None], renderer_class: type, # Renderer type, there is no superclass renderer yet ..... is_set_test_data_test: bool, last_frame: bool, show_diff: bool, size_frame: tuple, ) -> Callable[[], None]: """Create the real pytest test that will fail if the frames mismatch. Parameters ---------- file_path The path of the control frames. base_scene The base scene class. construct The construct method (= the test function) renderer_class The renderer base class. show_diff whether to visually show_diff (see --show_diff) Returns ------- Callable[[], None] The pytest test. """ if is_set_test_data_test: frames_tester: _FramesTester = _ControlDataWriter( file_path, size_frame=size_frame ) else: frames_tester = _FramesTester(file_path, show_diff=show_diff) file_writer_class = ( _make_scene_file_writer_class(frames_tester) if not last_frame else DummySceneFileWriter ) testRenderer = _make_test_renderer_class(renderer_class) def real_test() -> None: with frames_tester.testing(): sceneTested = _make_test_scene_class( base_scene=base_scene,
|
to visually show_diff (see --show_diff) Returns ------- Callable[[], None] The pytest test. """ if is_set_test_data_test: frames_tester: _FramesTester = _ControlDataWriter( file_path, size_frame=size_frame ) else: frames_tester = _FramesTester(file_path, show_diff=show_diff) file_writer_class = ( _make_scene_file_writer_class(frames_tester) if not last_frame else DummySceneFileWriter ) testRenderer = _make_test_renderer_class(renderer_class) def real_test() -> None: with frames_tester.testing(): sceneTested = _make_test_scene_class( base_scene=base_scene, construct_test=construct, # NOTE this is really ugly but it's due to the very bad design of the two renderers. # If you pass a custom renderer to the Scene, the Camera class given as an argument in the Scene # is not passed to the renderer. See __init__ of Scene. # This potentially prevents OpenGL testing. test_renderer=( testRenderer(file_writer_class=file_writer_class) if base_scene is not ThreeDScene else testRenderer( file_writer_class=file_writer_class, camera_class=ThreeDCamera, ) ), # testRenderer(file_writer_class=file_writer_class), ) scene_tested = sceneTested(skip_animations=True) scene_tested.render() if last_frame: frames_tester.check_frame(-1, scene_tested.renderer.get_frame()) return real_test def _control_data_path( test_file_path: str | None, module_name: str, test_name: str, setting_test: bool ) -> Path: if test_file_path is None: # For some reason, path to test file containing @frames_comparison could not # be determined. Use local directory instead. test_file_path = __file__ path = Path(test_file_path).absolute().parent / "control_data" / module_name if setting_test: # Create the directory if not existing. path.mkdir(exist_ok=True) if not setting_test and not path.exists(): raise Exception(f"The control frames directory can't be found in {path}") path = (path / test_name).with_suffix(".npz") if not setting_test and not path.is_file(): raise Exception( f"The control frame for the test {test_name} cannot be found in {path.parent}. " "Make sure you generated the control frames first.", ) return path def _config_test(last_frame: bool) -> ManimConfig: return ManimConfig().digest_file( str( Path(__file__).parent / ( "config_graphical_tests_monoframe.cfg" if last_frame else "config_graphical_tests_multiframes.cfg" ), ), ) ================================================ FILE: scripts/dev_changelog.py ================================================ #!/usr/bin/env python """Script to generate contributor and pull request lists. This script generates contributor and pull request lists for release changelogs using Github v3 protocol. Use requires an authentication token in order to have sufficient bandwidth, you can get one following the directions at `<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_ Don't add any scope, as the default is read access to public information. The token may be stored in an environment variable as you only get one chance to see it. Usage:: $ ./scripts/dev_changelog.py [OPTIONS] TOKEN PRIOR TAG [ADDITIONAL]... The output is utf8 rst. Dependencies ------------ - gitpython - pygithub Examples -------- From a bash command line with $GITHUB environment variable as the GitHub token:: $ ./scripts/dev_changelog.py $GITHUB v0.3.0 v0.4.0 This would generate 0.4.0-changelog.rst file and place it automatically under docs/source/changelog/. As another example, you may also run include PRs that have been excluded by providing a space separated list of ticket numbers after TAG:: $ ./scripts/dev_changelog.py $GITHUB v0.3.0 v0.4.0 1911 1234 1492 ... Note ---- This script was taken from Numpy under the terms of BSD-3-Clause license. """ from __future__ import annotations import concurrent.futures import datetime import re from collections import defaultdict from pathlib import Path from textwrap import dedent, indent import cloup from git import Repo from github import Github from tqdm import tqdm from manim.constants import CONTEXT_SETTINGS, EPILOG this_repo = Repo(str(Path(__file__).resolve().parent.parent)) PR_LABELS = { "breaking changes": "Breaking changes", "highlight": "Highlights", "pr:deprecation": "Deprecated classes and functions", "new
|
from collections import defaultdict from pathlib import Path from textwrap import dedent, indent import cloup from git import Repo from github import Github from tqdm import tqdm from manim.constants import CONTEXT_SETTINGS, EPILOG this_repo = Repo(str(Path(__file__).resolve().parent.parent)) PR_LABELS = { "breaking changes": "Breaking changes", "highlight": "Highlights", "pr:deprecation": "Deprecated classes and functions", "new feature": "New features", "enhancement": "Enhancements", "pr:bugfix": "Fixed bugs", "documentation": "Documentation-related changes", "testing": "Changes concerning the testing system", "infrastructure": "Changes to our development infrastructure", "maintenance": "Code quality improvements and similar refactors", "revert": "Changes that needed to be reverted again", "release": "New releases", "unlabeled": "Unclassified changes", } SILENT_CONTRIBUTORS = [ "dependabot[bot]", ] def update_citation(version, date): current_directory = Path(__file__).parent parent_directory = current_directory.parent contents = (current_directory / "TEMPLATE.cff").read_text() contents = contents.replace("<version>", version) contents = contents.replace("<date_released>", date) with (parent_directory / "CITATION.cff").open("w", newline="\n") as f: f.write(contents) def process_pullrequests(lst, cur, github_repo, pr_nums): lst_commit = github_repo.get_commit(sha=this_repo.git.rev_list("-1", lst)) lst_date = lst_commit.commit.author.date authors = set() reviewers = set() pr_by_labels = defaultdict(list) with concurrent.futures.ThreadPoolExecutor() as executor: future_to_num = { executor.submit(github_repo.get_pull, num): num for num in pr_nums } for future in tqdm( concurrent.futures.as_completed(future_to_num), "Processing PRs" ): pr = future.result() authors.add(pr.user) reviewers = reviewers.union(rev.user for rev in pr.get_reviews()) pr_labels = [label.name for label in pr.labels] for label in PR_LABELS: if label in pr_labels: pr_by_labels[label].append(pr) break # ensure that PR is only added in one category else: pr_by_labels["unlabeled"].append(pr) # identify first-time contributors: author_names = [] for author in authors: name = author.name if author.name is not None else author.login if name in SILENT_CONTRIBUTORS: continue if github_repo.get_commits(author=author, until=lst_date).totalCount == 0: name += " +" author_names.append(name) reviewer_names = [] for reviewer in reviewers: name = reviewer.name if reviewer.name is not None else reviewer.login if name in SILENT_CONTRIBUTORS: continue reviewer_names.append(name) # Sort items in pr_by_labels for i in pr_by_labels: pr_by_labels[i] = sorted(pr_by_labels[i], key=lambda pr: pr.number) return { "authors": sorted(author_names), "reviewers": sorted(reviewer_names), "PRs": pr_by_labels, } def get_pr_nums(lst, cur): print("Getting PR Numbers:") prnums = [] # From regular merges merges = this_repo.git.log("--oneline", "--merges", f"{lst}..{cur}") issues = re.findall(r".*\(\#(\d+)\)", merges) prnums.extend(int(s) for s in issues) # From fast forward squash-merges commits = this_repo.git.log( "--oneline", "--no-merges", "--first-parent", f"{lst}..{cur}", ) split_commits = list( filter( lambda x: not any( ["pre-commit autoupdate" in x, "New Crowdin updates" in x] ), commits.split("\n"), ), ) commits = "\n".join(split_commits) issues = re.findall(r"^.*\(\#(\d+)\)$", commits, re.M) prnums.extend(int(s) for s in issues) print(prnums) return prnums def get_summary(body): pattern = '<!--changelog-start-->([^"]*)<!--changelog-end-->' try: has_changelog_pattern = re.search(pattern, body) if has_changelog_pattern: return has_changelog_pattern.group()[22:-21].strip() except Exception: print(f"Error parsing body for changelog: {body}") @cloup.command( context_settings=CONTEXT_SETTINGS, epilog=EPILOG, ) @cloup.argument("token") @cloup.argument("prior") @cloup.argument("tag") @cloup.argument( "additional", nargs=-1, required=False, type=int, ) @cloup.option( "-o", "--outfile", type=str, help="Path and file name of the changelog output.", ) def main(token, prior, tag, additional, outfile): """Generate Changelog/List of contributors/PRs for release. TOKEN is your GitHub Personal Access Token. PRIOR is the tag/commit SHA of the previous release. TAG is the tag of the new release. ADDITIONAL includes additional PR(s) that have not been recognized automatically. """ lst_release, cur_release = prior, tag github = Github(token) github_repo = github.get_repo("ManimCommunity/manim") pr_nums = get_pr_nums(lst_release, cur_release) if additional: print(f"Adding {additional} to the mix!") pr_nums = pr_nums + list(additional) # document authors contributions
|
TAG is the tag of the new release. ADDITIONAL includes additional PR(s) that have not been recognized automatically. """ lst_release, cur_release = prior, tag github = Github(token) github_repo = github.get_repo("ManimCommunity/manim") pr_nums = get_pr_nums(lst_release, cur_release) if additional: print(f"Adding {additional} to the mix!") pr_nums = pr_nums + list(additional) # document authors contributions = process_pullrequests(lst_release, cur_release, github_repo, pr_nums) authors = contributions["authors"] reviewers = contributions["reviewers"] # update citation file today = datetime.date.today() update_citation(tag, str(today)) if not outfile: outfile = ( Path(__file__).resolve().parent.parent / "docs" / "source" / "changelog" ) outfile = outfile / f"{tag[1:] if tag.startswith('v') else tag}-changelog.rst" else: outfile = Path(outfile).resolve() with outfile.open("w", encoding="utf8", newline="\n") as f: f.write("*" * len(tag) + "\n") f.write(f"{tag}\n") f.write("*" * len(tag) + "\n\n") f.write(f":Date: {today.strftime('%B %d, %Y')}\n\n") heading = "Contributors" f.write(f"{heading}\n") f.write("=" * len(heading) + "\n\n") f.write( dedent( f"""\ A total of {len(set(authors).union(set(reviewers)))} people contributed to this release. People with a '+' by their names authored a patch for the first time.\n """, ), ) for author in authors: f.write(f"* {author}\n") f.write("\n") f.write( dedent( """ The patches included in this release have been reviewed by the following contributors.\n """, ), ) for reviewer in reviewers: f.write(f"* {reviewer}\n") # document pull requests heading = "Pull requests merged" f.write("\n") f.write(heading + "\n") f.write("=" * len(heading) + "\n\n") f.write( f"A total of {len(pr_nums)} pull requests were merged for this release.\n\n", ) pr_by_labels = contributions["PRs"] for label in PR_LABELS: pr_of_label = pr_by_labels[label] if pr_of_label: heading = PR_LABELS[label] f.write(f"{heading}\n") f.write("-" * len(heading) + "\n\n") for PR in pr_by_labels[label]: num = PR.number title = PR.title label = PR.labels f.write(f"* :pr:`{num}`: {title}\n") overview = get_summary(PR.body) if overview: f.write(indent(f"{overview}\n\n", " ")) else: f.write("\n\n") print(f"Wrote changelog to: {outfile}") if __name__ == "__main__": main() ================================================ FILE: scripts/extract_frames.py ================================================ from __future__ import annotations import pathlib import sys import numpy as np from PIL import Image def main(): if len(sys.argv) != 3: print_usage() sys.exit(1) npz_file = sys.argv[1] output_folder = pathlib.Path(sys.argv[2]) if not output_folder.exists(): output_folder.mkdir(parents=True) data = np.load(npz_file) if "frame_data" not in data: print("The given file did not have frame_data.") print("Are you sure this is from a Manim Graphical Unit Test?") sys.exit(2) frames = data["frame_data"] for i, frame in enumerate(frames): img = Image.fromarray(frame) img.save(output_folder / f"frame{i}.png") print(f"Saved {len(frames)} frames to {output_folder}") def print_usage(): print("Manim Graphical Test Frame Extractor") print( "This tool outputs the frames of a Graphical Unit Test " "stored within a .npz file, typically found under " r"//tests/test_graphical_units/control_data" ) print() print("usage:") print("python3 extract_frames.py npz_file output_directory") if __name__ == "__main__": main() ================================================ FILE: scripts/make_and_open_docs.py ================================================ from __future__ import annotations import subprocess import sys import webbrowser from pathlib import Path path_makefile = Path(__file__).resolve().parents[1] / "docs" subprocess.run(["make", "html"], cwd=path_makefile) website = (path_makefile / "build" / "html" / "index.html").absolute().as_uri() try: # Allows you to pass a custom browser if you want. webbrowser.get(sys.argv[1]).open_new_tab(f"{website}") except IndexError: webbrowser.open_new_tab(f"{website}") ================================================ FILE: scripts/TEMPLATE.cff ================================================ # YAML 1.2 --- authors: - name: "The Manim Community Developers" cff-version: "1.2.0" date-released: <date_released> license: MIT message: "We acknowledge the importance of good software to support research, and we note that research becomes more valuable when it is communicated effectively. To demonstrate the value
|
webbrowser.open_new_tab(f"{website}") ================================================ FILE: scripts/TEMPLATE.cff ================================================ # YAML 1.2 --- authors: - name: "The Manim Community Developers" cff-version: "1.2.0" date-released: <date_released> license: MIT message: "We acknowledge the importance of good software to support research, and we note that research becomes more valuable when it is communicated effectively. To demonstrate the value of Manim, we ask that you cite Manim in your work." title: Manim – Mathematical Animation Framework url: "https://www.manicommunity/" version: "<version>" ... ================================================ FILE: scripts/template_docsting_with_example.py ================================================ # see more documentation guidelines online here: https://github.com/ManimCommunity/manim/wiki/Documentation-guidelines-(WIP) from __future__ import annotations class SomeClass: """A one line description of the Class. A short paragraph providing more details. Extended Summary Parameters ---------- scale_factor The factor used for scaling. Returns ------- :class:`~.VMobject` Returns the modified :class:`~.VMobject`. Tests ----- Yields ------- Receives ---------- Other Parameters ----------------- Raises ------ :class:`TypeError` If one element of the list is not an instance of VMobject Warns ----- Warnings -------- Notes ----- Examples -------- .. manim:: AddTextLetterByLetterScene :save_last_frame: class AddTextLetterByLetterScene(Scene): def construct(self): t = Text("Hello World word by word") self.play(AddTextWordByWord(t)) See Also -------- :class:`Create`, :class:`~.ShowPassingFlash` References ---------- Other useful directives: .. tip:: This is currently only possible for class:`~.Text` and not for class:`~.MathTex`. .. note:: This is something to note. """ ================================================ FILE: tests/__init__.py ================================================ [Empty file] ================================================ FILE: tests/assert_utils.py ================================================ from __future__ import annotations import os from pathlib import Path from pprint import pformat def assert_file_exists(filepath: str | os.PathLike) -> None: """Assert that filepath points to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath. This is mostly to have better assert message than using a raw assert filepath.is_file(). Parameters ---------- filepath Filepath to check. Raises ------ AssertionError If filepath does not point to a file (if the file does not exist or it's a dir). """ path = Path(filepath) if not path.is_file(): elems = pformat([path.name for path in path.parent.iterdir()]) message = f"{path.absolute()} is not a file. Other elements in the parent directory are \n{elems}" raise AssertionError(message) def assert_dir_exists(dirpath: str | os.PathLike) -> None: """Assert that directory exists. Parameters ---------- dirpath Path to directory to check. Raises ------ AssertionError If dirpath does not point to a directory (if the file does exist or it's a file). """ path = Path(dirpath) if not path.is_dir(): elems = pformat([path.name for path in list(path.parent.iterdir())]) message = f"{path.absolute()} is not a directory. Other elements in the parent directory are \n{elems}" raise AssertionError(message) def assert_dir_filled(dirpath: str | os.PathLike) -> None: """Assert that directory exists and contains at least one file or directory (or file like objects like symlinks on Linux). Parameters ---------- dirpath Path to directory to check. Raises ------ AssertionError If dirpath does not point to a directory (if the file does exist or it's a file) or the directory is empty. """ if not any(Path(dirpath).iterdir()): raise AssertionError(f"{dirpath} is an empty directory.") def assert_file_not_exists(filepath: str | os.PathLike) -> None: """Assert that filepath does not point to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath. This is mostly
|
or the directory is empty. """ if not any(Path(dirpath).iterdir()): raise AssertionError(f"{dirpath} is an empty directory.") def assert_file_not_exists(filepath: str | os.PathLike) -> None: """Assert that filepath does not point to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath. This is mostly to have better assert message than using a raw assert filepath.is_file(). Parameters ---------- filepath Filepath to check. Raises ------ AssertionError If filepath does point to a file. """ path = Path(filepath) if path.is_file(): elems = pformat([path.name for path in path.parent.iterdir()]) message = f"{path.absolute()} is a file. Other elements in the parent directory are \n{elems}" raise AssertionError(message) def assert_dir_not_exists(dirpath: str | os.PathLike) -> None: """Assert that directory does not exist. Parameters ---------- dirpath Path to directory to check. Raises ------ AssertionError If dirpath points to a directory. """ path = Path(dirpath) if path.is_dir(): elems = pformat([path.name for path in list(path.parent.iterdir())]) message = f"{path.absolute()} is a directory. Other elements in the parent directory are \n{elems}" raise AssertionError(message) def assert_shallow_dict_compare(a: dict, b: dict, message_start: str) -> None: """Assert that Directories ``a`` and ``b`` are the same. ``b`` is treated as the expected values that ``a`` shall abide by. Print helpful error with custom message start. """ mismatch: list[str] = [] for b_key, b_value in b.items(): if b_key not in a: mismatch.append(f"Missing item {b_key}: {b_value}") elif b_value != a[b_key]: mismatch.append(f"For {b_key} got {a[b_key]}, expected {b_value}") for a_key, a_value in a.items(): if a_key not in b: mismatch.append(f"Extraneous item {a_key}: {a_value}") mismatch_str = "\n".join(mismatch) assert len(mismatch) == 0, f"{message_start}\n{mismatch_str}" ================================================ FILE: tests/conftest.py ================================================ from __future__ import annotations import logging import sys from pathlib import Path import cairo import moderngl import pytest import manim def pytest_report_header(config): try: ctx = moderngl.create_standalone_context() info = ctx.info ctx.release() except Exception as e: raise Exception("Error while creating moderngl context") from e return ( f"\nCairo Version: {cairo.cairo_version()}", "\nOpenGL information", "------------------", f"vendor: {info['GL_VENDOR'].strip()}", f"renderer: {info['GL_RENDERER'].strip()}", f"version: {info['GL_VERSION'].strip()}\n", ) def pytest_addoption(parser): parser.addoption( "--skip_slow", action="store_true", default=False, help="Will skip all the slow marked tests. Slow tests are arbitrarily marked as such.", ) parser.addoption( "--show_diff", action="store_true", default=False, help="Will show a visual comparison if a graphical unit test fails.", ) parser.addoption( "--set_test", action="store_true", default=False, help="Will create the control data for EACH running tests. ", ) def pytest_configure(config): config.addinivalue_line("markers", "skip_end_to_end: mark test as end_to_end test") def pytest_collection_modifyitems(config, items): if not config.getoption("--skip_slow"): return else: slow_skip = pytest.mark.skip( reason="Slow test skipped due to --disable_slow flag.", ) for item in items: if "slow" in item.keywords: item.add_marker(slow_skip) @pytest.fixture(autouse=True) def temp_media_dir(tmpdir, monkeypatch, request): if isinstance(request.node, pytest.DoctestItem): monkeypatch.chdir(tmpdir) yield tmpdir else: with manim.tempconfig({"media_dir": str(tmpdir)}): assert manim.config.media_dir == str(tmpdir) yield tmpdir @pytest.fixture def manim_caplog(caplog): logger = logging.getLogger("manim") logger.propagate = True caplog.set_level(logging.INFO, logger="manim") yield caplog logger.propagate = False @pytest.fixture def config(): saved = manim.config.copy() manim.config.renderer = "cairo" # we need to return the actual config so that tests # using tempconfig pass yield manim.config manim.config.update(saved) @pytest.fixture def dry_run(config): config.dry_run = True @pytest.fixture(scope="session") def python_version(): # use the same python executable as it is running currently # rather than randomly calling using python or python3, which # may create
|
we need to return the actual config so that tests # using tempconfig pass yield manim.config manim.config.update(saved) @pytest.fixture def dry_run(config): config.dry_run = True @pytest.fixture(scope="session") def python_version(): # use the same python executable as it is running currently # rather than randomly calling using python or python3, which # may create problems. return sys.executable @pytest.fixture def reset_cfg_file(): cfgfilepath = Path(__file__).parent / "test_cli" / "manim.cfg" original = cfgfilepath.read_text() yield cfgfilepath.write_text(original) @pytest.fixture def using_opengl_renderer(config): """Standard fixture for running with opengl that makes tests use a standard_config.cfg with a temp dir.""" config.renderer = "opengl" yield # as a special case needed to manually revert back to cairo # due to side effects of setting the renderer config.renderer = "cairo" ================================================ FILE: tests/standard_config.cfg ================================================ [CLI] frame_rate = 15 pixel_height = 480 pixel_width = 300 verbosity = DEBUG ================================================ FILE: tests/template_generate_graphical_units_data.py ================================================ from __future__ import annotations from manim import * from tests.helpers.graphical_units import set_test_scene # Note: DO NOT COMMIT THIS FILE. The purpose of this template is to produce control data for graphical_units_data. As # soon as the test data is produced, please revert all changes you made to this file, so this template file will be # still available for others :) # More about graphical unit tests: https://github.com/ManimCommunity/manim/wiki/Testing#graphical-unit-test class YourClassTest(Scene): # e.g. RoundedRectangleTest def construct(self): circle = Circle() self.play(Animation(circle)) set_test_scene( YourClassTest, "INSERT_MODULE_NAME", ) # INSERT_MODULE_NAME can be e.g. "geometry" or "movements" ================================================ FILE: tests/test_camera.py ================================================ from __future__ import annotations from manim import MovingCamera, Square def test_movingcamera_auto_zoom(): camera = MovingCamera() square = Square() margin = 0.5 camera.auto_zoom([square], margin=margin, animate=False) assert camera.frame.height == square.height + margin ================================================ FILE: tests/test_code_mobject.py ================================================ import numpy as np from manim.mobject.text.code_mobject import Code from manim.utils.color.core import ManimColor def test_code_initialization_from_string(): code_string = """from manim import Scene, Square class FadeInSquare(Scene): def construct(self): s = Square() self.play(FadeIn(s)) self.play(s.animate.scale(2)) self.wait()""" rendered_code = Code( code_string=code_string, language="python", ) num_lines = len(code_string.split("\n")) assert len(rendered_code.code_lines) == num_lines assert len(rendered_code.line_numbers) == num_lines def test_code_initialization_from_file(): rendered_code = Code( code_file="tests/test_code_mobject.py", language="python", background="window", background_config={"fill_color": "#101010"}, ) assert len(rendered_code.code_lines) == len(rendered_code.line_numbers) assert rendered_code.background.fill_color == ManimColor("#101010") def test_line_heights_initial_whitespace(): rendered_code = Code( code_string="""print('Hello, World!') for _ in range(42): print('Hello, World!') """, language="python", ) np.testing.assert_almost_equal( rendered_code.code_lines[0].height, rendered_code.code_lines[2].height, ) ================================================ FILE: tests/test_config.py ================================================ from __future__ import annotations import tempfile from pathlib import Path import numpy as np import pytest from manim import WHITE, Scene, Square, Tex, Text, tempconfig from manim._config.utils import ManimConfig from tests.assert_utils import assert_dir_exists, assert_dir_filled, assert_file_exists def test_tempconfig(config): """Test the tempconfig context manager.""" original = config.copy() with tempconfig({"frame_width": 100, "frame_height": 42}): # check that config was modified correctly assert config["frame_width"] == 100 assert config["frame_height"] == 42 # check that no keys are missing and no new keys were added assert set(original.keys()) == set(config.keys()) # check that the keys are still untouched assert set(original.keys()) == set(config.keys()) # check that config is correctly restored for k, v in original.items(): if isinstance(v, np.ndarray): np.testing.assert_allclose(config[k], v) else: assert config[k] == v @pytest.mark.parametrize( ("format", "expected_file_extension"), [ ("mp4", ".mp4"), ("webm", ".webm"), ("mov", ".mov"), ("gif", ".mp4"), ], ) def test_resolve_file_extensions(config, format, expected_file_extension): config.format = format assert config.movie_file_extension == expected_file_extension class MyScene(Scene): def construct(self):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.