A community-maintained Python framework for creating mathematical animations.
Enforce formatting with CI (#221)
Devin Neal6e5770a85f62
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8331a393b..9889a4fff 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1,16 +1,39 @@name: CI-on:+on:push:branches:- masterpull_request:branches:- master+jobs:+ format:+ runs-on: ubuntu-latest+ steps:+ - name: Checkout the repository+ uses: actions/checkout@v2++ - name: Set up Python+ uses: actions/setup-python@v2+ with:+ python-version: 3.8++ - name: Install black+ run: pip install black++ - name: Check manim formatting+ run: black --check --diff manim++ - name: Check tests formatting+ run: black --check --diff tests++ - name: Check examples formatting+ run: black --check --diff example_scenes+test:runs-on: ${{ matrix.os }}strategy:- fail-fast: falsematrix:os: [ubuntu-latest, macos-latest, windows-latest]python: [3.6, 3.7, 3.8]diff --git a/example_scenes/basic.py b/example_scenes/basic.pyindex 33d4d6a0e..8245bfc58 100644--- a/example_scenes/basic.py+++ b/example_scenes/basic.py@@ -18,14 +18,10 @@ from manim import *class OpeningManimExample(Scene):def construct(self):title = TextMobject("This is some \\LaTeX")- basel = TexMobject(- "\\sum_{n=1}^\\infty "- "\\frac{1}{n^2} = \\frac{\\pi^2}{6}"- )+ basel = TexMobject("\\sum_{n=1}^\\infty " "\\frac{1}{n^2} = \\frac{\\pi^2}{6}")VGroup(title, basel).arrange(DOWN)self.play(- Write(title),- FadeInFrom(basel, UP),+ Write(title), FadeInFrom(basel, UP),)self.wait()@@ -51,24 +47,17 @@ class OpeningManimExample(Scene):self.wait()grid_transform_title = TextMobject(- "That was a non-linear function \\\\"- "applied to the grid"+ "That was a non-linear function \\\\" "applied to the grid")grid_transform_title.move_to(grid_title, UL)grid.prepare_for_nonlinear_transform()self.play(grid.apply_function,- lambda p: p + np.array([- np.sin(p[1]),- np.sin(p[0]),- 0,- ]),+ lambda p: p + np.array([np.sin(p[1]), np.sin(p[0]), 0,]),run_time=3,)self.wait()- self.play(- Transform(grid_title, grid_transform_title)- )+ self.play(Transform(grid_title, grid_transform_title))self.wait()@@ -88,25 +77,25 @@ class SquareToCircle(Scene):class WarpSquare(Scene):def construct(self):square = Square()- self.play(ApplyPointwiseFunction(- lambda point: complex_to_R3(np.exp(R3_to_complex(point))),- square- ))+ self.play(+ ApplyPointwiseFunction(+ lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square+ )+ )self.wait()class WriteStuff(Scene):def construct(self):example_text = TextMobject(- "This is a some text",- tex_to_color_map={"text": YELLOW}+ "This is a some text", tex_to_color_map={"text": YELLOW})example_tex = TexMobject("\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}",)group = VGroup(example_text, example_tex)group.arrange(DOWN)- group.set_width(config['frame_width'] - 2 * LARGE_BUFF)+ group.set_width(config["frame_width"] - 2 * LARGE_BUFF)self.play(Write(example_text))self.play(Write(example_tex))@@ -116,10 +105,7 @@ class WriteStuff(Scene):class UpdatersExample(Scene):def construct(self):decimal = DecimalNumber(- 0,- show_ellipsis=True,- num_decimal_places=3,- include_sign=True,+ 0, show_ellipsis=True, num_decimal_places=3, include_sign=True,)square = Square().to_edge(UP)@@ -127,58 +113,54 @@ class UpdatersExample(Scene):decimal.add_updater(lambda d: d.set_value(square.get_center()[1]))self.add(square, decimal)self.play(- square.to_edge, DOWN,- rate_func=there_and_back,- run_time=5,+ square.to_edge, DOWN, rate_func=there_and_back, run_time=5,)self.wait()+class VDictTest(Scene):def construct(self):square = Square().set_color(RED)circle = Circle().set_color(YELLOW).next_to(square, UP)# create dict from list of tuples each having key-mobject pair- pairs = [('s', square), ('c', circle)]+ pairs = [("s", square), ("c", circle)]my_dict = VDict(*pairs, show_keys=True)# display it just like a VGroup- self.play(- ShowCreation(my_dict)- )+ self.play(ShowCreation(my_dict))self.wait()-text = TextMobject("Some text").set_color(GREEN).next_to(square, DOWN)- #add like a VGroup- my_dict.add(('t', text))+ # add like a VGroup+ my_dict.add(("t", text))self.wait()-+rect = Rectangle().next_to(text, DOWN)# can also do key assignment like a python dict- my_dict['r'] = rect+ my_dict["r"] = rect# access submobjects like a python dict- my_dict['t'].set_color(PURPLE)- self.play(my_dict['t'].scale, 3)+ my_dict["t"].set_color(PURPLE)+ self.play(my_dict["t"].scale, 3)self.wait()# also supports python dict styled reassignment- my_dict['t'] = TextMobject("Some other text").set_color(BLUE)+ my_dict["t"] = TextMobject("Some other text").set_color(BLUE)self.wait()# remove submojects by key- my_dict.remove('t')+ my_dict.remove("t")self.wait()- self.play(Uncreate(my_dict['s']))+ self.play(Uncreate(my_dict["s"]))self.wait()- self.play(FadeOut(my_dict['c']))+ self.play(FadeOut(my_dict["c"]))self.wait()- self.play(FadeOutAndShift(my_dict['r'], DOWN))+ self.play(FadeOutAndShift(my_dict["r"], DOWN))self.wait()# iterate through all submobjects currently associated with my_dict@@ -186,4 +168,5 @@ class VDictTest(Scene):self.play(ShowCreation(submob))self.wait()+# See old_projects folder for many, many morediff --git a/example_scenes/customtex.py b/example_scenes/customtex.pyindex 10fb3b4e8..64a9ab59d 100644--- a/example_scenes/customtex.py+++ b/example_scenes/customtex.py@@ -1,5 +1,6 @@from manim import *+class TexTemplateFromCLI(Scene):"""This scene uses a custom TexTemplate file.The path of the TexTemplate _must_ be passed with the command line@@ -8,9 +9,10 @@ class TexTemplateFromCLI(Scene):This scene will fail to render if a tex_template.tex that doesn'timport esvect is passed, and will throw a LaTeX error in that case."""+def construct(self):text = TexMobject(r"\vv{vb}")- #text=TextMobject(r"$\vv{vb}$")+ # text=TextMobject(r"$\vv{vb}$")self.play(Write(text))@@ -18,11 +20,12 @@ class InCodeTexTemplate(Scene):"""This example scene demonstrates how to modify the tex templatefor a particular scene from the code for the scene itself."""+def construct(self):tpl = TexTemplate()tpl.append_package(["esvect", ["f"]])- config['tex_template'] = tpl+ config["tex_template"] = tpl- #text=TextMobject(r"$\vv{vb}$")+ # text=TextMobject(r"$\vv{vb}$")text = TexMobject(r"\vv{vb}")self.play(Write(text))diff --git a/manim/__main__.py b/manim/__main__.pyindex fed9b7827..6020af84a 100644--- a/manim/__main__.py+++ b/manim/__main__.py@@ -13,7 +13,7 @@ from .scene.scene import Scenefrom .utils.sounds import play_error_soundfrom .utils.sounds import play_finish_soundfrom . import constants-from .logger import logger,console+from .logger import logger, consoledef open_file_if_needed(file_writer):@@ -21,10 +21,9 @@ def open_file_if_needed(file_writer):curr_stdout = sys.stdoutsys.stdout = open(os.devnull, "w")- open_file = any([- file_writer_config["preview"],- file_writer_config["show_file_in_finder"]- ])+ open_file = any(+ [file_writer_config["preview"], file_writer_config["show_file_in_finder"]]+ )if open_file:current_os = platform.system()file_paths = []@@ -52,7 +51,7 @@ def open_file_if_needed(file_writer):commands.append(file_path)# commands.append("-g")- FNULL = open(os.devnull, 'w')+ FNULL = open(os.devnull, "w")sp.call(commands, stdout=FNULL, stderr=sp.STDOUT)FNULL.close()@@ -62,10 +61,12 @@ def open_file_if_needed(file_writer):def is_child_scene(obj, module):- return (inspect.isclass(obj)- and issubclass(obj, Scene)- and obj != Scene- and obj.__module__.startswith(module.__name__))+ return (+ inspect.isclass(obj)+ and issubclass(obj, Scene)+ and obj != Scene+ and obj.__module__.startswith(module.__name__)+ )def prompt_user_for_choice(scene_classes):@@ -76,9 +77,13 @@ def prompt_user_for_choice(scene_classes):console.print(f"{count}: {name}", style="logging.level.info")num_to_class[count] = scene_classtry:- user_input = console.input(f"[log.message] {constants.CHOOSE_NUMBER_MESSAGE} [/log.message]")- return [num_to_class[int(num_str)]- for num_str in re.split(r"\s*,\s*", user_input.strip())]+ user_input = console.input(+ f"[log.message] {constants.CHOOSE_NUMBER_MESSAGE} [/log.message]"+ )+ return [+ num_to_class[int(num_str)]+ for num_str in re.split(r"\s*,\s*", user_input.strip())+ ]except KeyError:logger.error(constants.INVALID_NUMBER_MESSAGE)sys.exit(2)@@ -101,34 +106,35 @@ def get_scenes_to_render(scene_classes):found = Truebreakif not found and (scene_name != ""):- logger.error(- constants.SCENE_NOT_FOUND_MESSAGE.format(- scene_name- )- )+ logger.error(constants.SCENE_NOT_FOUND_MESSAGE.format(scene_name))if result:return result- return [scene_classes[0]] if len(scene_classes) == 1 else prompt_user_for_choice(scene_classes)+ return (+ [scene_classes[0]]+ if len(scene_classes) == 1+ else prompt_user_for_choice(scene_classes)+ )def get_scene_classes_from_module(module):return [member[1]- for member in inspect.getmembers(- module,- lambda x: is_child_scene(x, module)- )+ for member in inspect.getmembers(module, lambda x: is_child_scene(x, module))]def get_module(file_name):if 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):")+ 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.warn("Didn't find an import statement for Manim. Importing automatically...")- code="from manim import *\n"+code+ logger.warn(+ "Didn't find an import statement for Manim. Importing automatically..."+ )+ code = "from manim import *\n" + codelogger.info("Rendering animation from typed code...")try:exec(code, module.__dict__)@@ -140,13 +146,13 @@ def get_module(file_name):if os.path.exists(file_name):if file_name[-3:] != ".py":raise Exception(f"{file_name} is not a valid Manim python script.")- module_name = file_name[:-3].replace(os.sep, '.').split('.')[-1]+ module_name = file_name[:-3].replace(os.sep, ".").split(".")[-1]spec = importlib.util.spec_from_file_location(module_name, file_name)module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)return moduleelse:- raise FileNotFoundError(f'{file_name} not found')+ raise FileNotFoundError(f"{file_name} not found")def main():diff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex 3abe8ee8f..329baec1b 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -28,7 +28,7 @@ class Animation(object):}def __init__(self, mobject, **kwargs):- assert(isinstance(mobject, Mobject))+ assert isinstance(mobject, Mobject)digest_config(self, kwargs)self.mobject = mobject@@ -73,10 +73,9 @@ class Animation(object):return self.mobject, self.starting_mobjectdef get_all_families_zipped(self):- return zip(*[- mob.family_members_with_points()- for mob in self.get_all_mobjects()- ])+ return zip(+ *[mob.family_members_with_points() for mob in self.get_all_mobjects()]+ )def update_mobjects(self, dt):"""@@ -93,10 +92,7 @@ class Animation(object):# The surrounding scene typically handles# updating of self.mobject. Besides, in# most cases its updating is suspended anyway- return list(filter(- lambda m: m is not self.mobject,- self.get_all_mobjects()- ))+ return list(filter(lambda m: m is not self.mobject, self.get_all_mobjects()))def copy(self):return deepcopy(self)@@ -157,4 +153,4 @@ class Animation(object):return selfdef is_remover(self):- return self.remover\ No newline at end of file+ return self.removerdiff --git a/manim/animation/composition.py b/manim/animation/composition.pyindex b739707a9..7c5c5f04b 100644--- a/manim/animation/composition.py+++ b/manim/animation/composition.py@@ -30,9 +30,9 @@ class AnimationGroup(Animation):digest_config(self, kwargs)self.animations = animationsif self.group is None:- self.group = Group(*remove_list_redundancies(- [anim.mobject for anim in animations]- ))+ self.group = Group(+ *remove_list_redundancies([anim.mobject for anim in animations])+ )self.init_run_time()Animation.__init__(self, self.group, **kwargs)@@ -59,9 +59,7 @@ class AnimationGroup(Animation):def init_run_time(self):self.build_animations_with_timings()if self.anims_with_timings:- self.max_end_time = np.max([- awt[2] for awt in self.anims_with_timings- ])+ self.max_end_time = np.max([awt[2] for awt in self.anims_with_timings])else:self.max_end_time = 0if self.run_time is None:@@ -77,14 +75,10 @@ class AnimationGroup(Animation):for anim in self.animations:start_time = curr_timeend_time = start_time + anim.get_run_time()- self.anims_with_timings.append(- (anim, start_time, end_time)- )+ self.anims_with_timings.append((anim, start_time, end_time))# Start time of next animation is based on# the lag_ratio- curr_time = interpolate(- start_time, end_time, self.lag_ratio- )+ curr_time = interpolate(start_time, end_time, self.lag_ratio)def interpolate(self, alpha):# Note, if the run_time of AnimationGroup has been@@ -98,10 +92,7 @@ class AnimationGroup(Animation):if anim_time == 0:sub_alpha = 0else:- sub_alpha = np.clip(- (time - start_time) / anim_time,- 0, 1- )+ sub_alpha = np.clip((time - start_time) / anim_time, 0, 1)anim.interpolate(sub_alpha)@@ -111,7 +102,7 @@ class Succession(AnimationGroup):}def begin(self):- assert(len(self.animations) > 0)+ assert len(self.animations) > 0self.init_run_time()self.active_animation = self.animations[0]self.active_animation.begin()@@ -123,9 +114,7 @@ class Succession(AnimationGroup):self.active_animation.update_mobjects(dt)def interpolate(self, alpha):- index, subalpha = integer_interpolate(- 0, len(self.animations), alpha- )+ index, subalpha = integer_interpolate(0, len(self.animations), alpha)animation = self.animations[index]if animation is not self.active_animation:self.active_animation.finish()@@ -155,8 +144,5 @@ class LaggedStartMap(LaggedStart):anim_kwargs = dict(kwargs)if "lag_ratio" in anim_kwargs:anim_kwargs.pop("lag_ratio")- animations = [- AnimationClass(*args, **anim_kwargs)- for args in args_list- ]- super().__init__(*animations, **kwargs)\ No newline at end of file+ animations = [AnimationClass(*args, **anim_kwargs) for args in args_list]+ super().__init__(*animations, **kwargs)diff --git a/manim/animation/creation.py b/manim/animation/creation.pyindex 4e42e739c..bcab8b5cc 100644--- a/manim/animation/creation.py+++ b/manim/animation/creation.py@@ -18,9 +18,7 @@ class ShowPartial(Animation):"""def interpolate_submobject(self, submob, start_submob, alpha):- submob.pointwise_become_partial(- start_submob, *self.get_bounds(alpha)- )+ submob.pointwise_become_partial(start_submob, *self.get_bounds(alpha))def get_bounds(self, alpha):raise Exception("Not Implemented")@@ -36,10 +34,7 @@ class ShowCreation(ShowPartial):class Uncreate(ShowCreation):- CONFIG = {- "rate_func": lambda t: smooth(1 - t),- "remover": True- }+ CONFIG = {"rate_func": lambda t: smooth(1 - t), "remover": True}class DrawBorderThenFill(Animation):@@ -58,9 +53,7 @@ class DrawBorderThenFill(Animation):def check_validity_of_input(self, vmobject):if not isinstance(vmobject, VMobject):- raise Exception(- "DrawBorderThenFill only works for VMobjects"- )+ raise Exception("DrawBorderThenFill only works for VMobjects")def begin(self):self.outline = self.get_outline()@@ -70,10 +63,7 @@ class DrawBorderThenFill(Animation):outline = self.mobject.copy()outline.set_fill(opacity=0)for sm in outline.family_members_with_points():- sm.set_stroke(- color=self.get_stroke_color(sm),- width=self.stroke_width- )+ sm.set_stroke(color=self.get_stroke_color(sm), width=self.stroke_width)return outlinedef get_stroke_color(self, vmobject):@@ -89,9 +79,7 @@ class DrawBorderThenFill(Animation):def interpolate_submobject(self, submob, start, outline, alpha):index, subalpha = integer_interpolate(0, 2, alpha)if index == 0:- submob.pointwise_become_partial(- outline, 0, subalpha- )+ submob.pointwise_become_partial(outline, 0, subalpha)submob.match_style(outline)else:submob.interpolate(outline, start, subalpha)@@ -140,23 +128,28 @@ class ShowIncreasingSubsets(Animation):def update_submobject_list(self, index):self.mobject.submobjects = self.all_submobs[:index]+class AddTextLetterByLetter(ShowIncreasingSubsets):"""Add a Text Object letter by letter on the scene. Use time_per_char to change frequency of appearance of the letters."""+CONFIG = {"suspend_mobject_updating": False,"int_func": np.ceil,- "rate_func" : linear,+ "rate_func": linear,"time_per_char": 0.1,}def __init__(self, text, **kwargs):digest_config(self, kwargs)-- self.run_time = np.max((0.06, self.time_per_char)) * len(text) #Time_per_char must be above 0.06. Otherwise the animation doesn't finish.++ self.run_time = np.max((0.06, self.time_per_char)) * len(+ text+ ) # Time_per_char must be above 0.06. Otherwise the animation doesn't finish.super().__init__(text, **kwargs)+class ShowSubmobjectsOneByOne(ShowIncreasingSubsets):CONFIG = {"int_func": np.ceil,@@ -186,11 +179,13 @@ class AddTextWordByWord(Succession):def __init__(self, text_mobject, **kwargs):digest_config(self, kwargs)tpc = self.time_per_char- anims = it.chain(*[- [- ShowIncreasingSubsets(word, run_time=tpc * len(word)),- Animation(word, run_time=0.005 * len(word)**1.5),+ anims = it.chain(+ *[+ [+ ShowIncreasingSubsets(word, run_time=tpc * len(word)),+ Animation(word, run_time=0.005 * len(word) ** 1.5),+ ]+ for word in text_mobject]- for word in text_mobject- ])- super().__init__(*anims, **kwargs)\ No newline at end of file+ )+ super().__init__(*anims, **kwargs)diff --git a/manim/animation/fading.py b/manim/animation/fading.pyindex 8d0ade091..5f66ec817 100644--- a/manim/animation/fading.py+++ b/manim/animation/fading.py@@ -67,6 +67,7 @@ class FadeInFromDown(FadeInFrom):Identical to FadeInFrom, just with a name thatcommunicates the default"""+CONFIG = {"direction": DOWN,"lag_ratio": DEFAULT_ANIMATION_LAG_RATIO,@@ -74,7 +75,9 @@ class FadeInFromDown(FadeInFrom):def __init__(self, mobject, **kwargs):super().__init__(mobject, direction=DOWN, **kwargs)- logger.warning("FadeInFromDown is deprecated and will eventually disappear. Please use FadeInFrom(<mobject>, direction=DOWN, <other_args>) instead.")+ logger.warning(+ "FadeInFromDown is deprecated and will eventually disappear. Please use FadeInFrom(<mobject>, direction=DOWN, <other_args>) instead."+ )class FadeOutAndShift(FadeOut):@@ -98,13 +101,16 @@ class FadeOutAndShiftDown(FadeOutAndShift):Identical to FadeOutAndShift, just with a name thatcommunicates the default"""+CONFIG = {"direction": DOWN,}def __init__(self, mobject, **kwargs):super().__init__(mobject, direction=DOWN, **kwargs)- logger.warning("FadeOutAndShiftDown is deprecated and will eventually disappear. Please use FadeOutAndShift(<mobject>, direction=DOWN, <other_args>) instead.")+ logger.warning(+ "FadeOutAndShiftDown is deprecated and will eventually disappear. Please use FadeOutAndShift(<mobject>, direction=DOWN, <other_args>) instead."+ )class FadeInFromPoint(FadeIn):@@ -139,23 +145,18 @@ class VFadeIn(Animation):"""VFadeIn and VFadeOut only work for VMobjects,"""+CONFIG = {"suspend_mobject_updating": False,}def interpolate_submobject(self, submob, start, alpha):- submob.set_stroke(- opacity=interpolate(0, start.get_stroke_opacity(), alpha)- )- submob.set_fill(- opacity=interpolate(0, start.get_fill_opacity(), alpha)- )+ submob.set_stroke(opacity=interpolate(0, start.get_stroke_opacity(), alpha))+ submob.set_fill(opacity=interpolate(0, start.get_fill_opacity(), alpha))class VFadeOut(VFadeIn):- CONFIG = {- "remover": True- }+ CONFIG = {"remover": True}def interpolate_submobject(self, submob, start, alpha):super().interpolate_submobject(submob, start, 1 - alpha)diff --git a/manim/animation/growing.py b/manim/animation/growing.pyindex b6c880f58..fe3c9249f 100644--- a/manim/animation/growing.py+++ b/manim/animation/growing.py@@ -1,4 +1,5 @@from ..animation.transform import Transform+# from ..utils.paths import counterclockwise_pathfrom ..constants import PIdiff --git a/manim/animation/indication.py b/manim/animation/indication.pyindex 43bc6d010..fd6710c1b 100644--- a/manim/animation/indication.py+++ b/manim/animation/indication.py@@ -39,14 +39,12 @@ class FocusOn(Transform):def create_target(self):little_dot = Dot(radius=0)little_dot.set_fill(self.color, opacity=self.opacity)- little_dot.add_updater(- lambda d: d.move_to(self.focus_point)- )+ little_dot.add_updater(lambda d: d.move_to(self.focus_point))return little_dotdef create_starting_mobject(self):return Dot(- radius=config['frame_x_radius'] + config['frame_y_radius'],+ radius=config["frame_x_radius"] + config["frame_y_radius"],stroke_width=0,fill_color=self.color,fill_opacity=0,@@ -83,9 +81,7 @@ class Flash(AnimationGroup):self.lines = self.create_lines()animations = self.create_line_anims()super().__init__(- *animations,- group=self.lines,- **kwargs,+ *animations, group=self.lines, **kwargs,)def create_lines(self):@@ -101,19 +97,14 @@ class Flash(AnimationGroup):return linesdef create_line_anims(self):- return [- ShowCreationThenDestruction(line)- for line in self.lines- ]+ return [ShowCreationThenDestruction(line) for line in self.lines]class CircleIndicate(Indicate):CONFIG = {"rate_func": there_and_back,"remover": True,- "circle_config": {- "color": YELLOW,- },+ "circle_config": {"color": YELLOW,},}def __init__(self, mobject, **kwargs):@@ -164,11 +155,7 @@ class ShowCreationThenFadeOut(Succession):}def __init__(self, mobject, **kwargs):- super().__init__(- ShowCreation(mobject),- FadeOut(mobject),- **kwargs- )+ super().__init__(ShowCreation(mobject), FadeOut(mobject), **kwargs)class AnimationOnSurroundingRectangle(AnimationGroup):@@ -177,7 +164,7 @@ class AnimationOnSurroundingRectangle(AnimationGroup):# Function which takes in a rectangle, and spits# out some animation. Could be some animation class,# could be something more- "rect_animation": Animation+ "rect_animation": Animation,}def __init__(self, mobject, **kwargs):@@ -189,33 +176,24 @@ class AnimationOnSurroundingRectangle(AnimationGroup):rect = self.get_rect()rect.add_updater(lambda r: r.move_to(mobject))- super().__init__(- self.rect_animation(rect, **kwargs),- )+ super().__init__(self.rect_animation(rect, **kwargs),)def get_rect(self):return SurroundingRectangle(- self.mobject_to_surround,- **self.surrounding_rectangle_config+ self.mobject_to_surround, **self.surrounding_rectangle_config)class ShowPassingFlashAround(AnimationOnSurroundingRectangle):- CONFIG = {- "rect_animation": ShowPassingFlash- }+ CONFIG = {"rect_animation": ShowPassingFlash}class ShowCreationThenDestructionAround(AnimationOnSurroundingRectangle):- CONFIG = {- "rect_animation": ShowCreationThenDestruction- }+ CONFIG = {"rect_animation": ShowCreationThenDestruction}class ShowCreationThenFadeAround(AnimationOnSurroundingRectangle):- CONFIG = {- "rect_animation": ShowCreationThenFadeOut- }+ CONFIG = {"rect_animation": ShowCreationThenFadeOut}class ApplyWave(Homotopy):@@ -234,7 +212,7 @@ class ApplyWave(Homotopy):def homotopy(x, y, z, t):alpha = (x - left_x) / (right_x - left_x)power = np.exp(2.0 * (alpha - 0.5))- nudge = there_and_back(t**power)+ nudge = there_and_back(t ** power)return np.array([x, y, z]) + nudge * vectsuper().__init__(homotopy, mobject, **kwargs)@@ -262,11 +240,11 @@ class WiggleOutThenIn(Animation):submobject.points[:, :] = starting_sumobject.pointssubmobject.scale(interpolate(1, self.scale_value, there_and_back(alpha)),- about_point=self.get_scale_about_point()+ about_point=self.get_scale_about_point(),)submobject.rotate(wiggle(alpha, self.n_wiggles) * self.rotation_angle,- about_point=self.get_rotate_about_point()+ about_point=self.get_rotate_about_point(),)@@ -276,4 +254,4 @@ class TurnInsideOut(Transform):}def create_target(self):- return self.mobject.copy().reverse_points()\ No newline at end of file+ return self.mobject.copy().reverse_points()diff --git a/manim/animation/movement.py b/manim/animation/movement.pyindex fee1bb9c3..de1dea0f1 100644--- a/manim/animation/movement.py+++ b/manim/animation/movement.py@@ -22,8 +22,7 @@ class Homotopy(Animation):def interpolate_submobject(self, submob, start, alpha):submob.points = start.pointssubmob.apply_function(- self.function_at_time_t(alpha),- **self.apply_function_kwargs+ self.function_at_time_t(alpha), **self.apply_function_kwargs)@@ -38,9 +37,11 @@ class ComplexHomotopy(Homotopy):"""Complex Hootopy a function Cx[0, 1] to C"""+def homotopy(x, y, z, t):c = complex_homotopy(complex(x, y), t)return (c.real, c.imag, z)+Homotopy.__init__(self, homotopy, mobject, **kwargs)@@ -58,9 +59,7 @@ class PhaseFlow(Animation):def interpolate_mobject(self, alpha):if hasattr(self, "last_alpha"):dt = self.virtual_time * (alpha - self.last_alpha)- self.mobject.apply_function(- lambda p: p + dt * self.function(p)- )+ self.mobject.apply_function(lambda p: p + dt * self.function(p))self.last_alpha = alpha@@ -75,4 +74,4 @@ class MoveAlongPath(Animation):def interpolate_mobject(self, alpha):point = self.path.point_from_proportion(alpha)- self.mobject.move_to(point)\ No newline at end of file+ self.mobject.move_to(point)diff --git a/manim/animation/numbers.py b/manim/animation/numbers.pyindex df3a373ae..98e6b1f6d 100644--- a/manim/animation/numbers.py+++ b/manim/animation/numbers.py@@ -18,35 +18,31 @@ class ChangingDecimal(Animation):def check_validity_of_input(self, decimal_mob):if not isinstance(decimal_mob, DecimalNumber):- raise Exception(- "ChangingDecimal can only take "- "in a DecimalNumber"- )+ raise Exception("ChangingDecimal can only take " "in a DecimalNumber")def yell_about_depricated_configuration(self, **kwargs):# Obviously this would optimally be removed at# some point.for attr in ["tracked_mobject", "position_update_func"]:if attr in kwargs:- warnings.warn("""+ warnings.warn(+ """Don't use {} for ChangingDecimal,that functionality has been depricatedand you should use a mobject updaterinstead- """.format(attr)- )+ """.format(+ attr+ )+ )def interpolate_mobject(self, alpha):- self.mobject.set_value(- self.number_update_func(alpha)- )+ self.mobject.set_value(self.number_update_func(alpha))class ChangeDecimalToValue(ChangingDecimal):def __init__(self, decimal_mob, target_number, **kwargs):start_number = decimal_mob.numbersuper().__init__(- decimal_mob,- lambda a: interpolate(start_number, target_number, a),- **kwargs- )\ No newline at end of file+ decimal_mob, lambda a: interpolate(start_number, target_number, a), **kwargs+ )diff --git a/manim/animation/rotation.py b/manim/animation/rotation.pyindex 232eb79d5..f0acba243 100644--- a/manim/animation/rotation.py+++ b/manim/animation/rotation.py@@ -49,4 +49,4 @@ class Rotate(Transform):about_point=self.about_point,about_edge=self.about_edge,)- return target\ No newline at end of file+ return targetdiff --git a/manim/animation/specialized.py b/manim/animation/specialized.pyindex 4438ead65..f5fc3fa36 100644--- a/manim/animation/specialized.py+++ b/manim/animation/specialized.py@@ -30,10 +30,9 @@ class MoveCar(ApplyMethod):def begin(self):super().begin()car = self.mobject- distance = get_norm(op.sub(- self.target_mobject.get_right(),- self.starting_mobject.get_right(),- ))+ distance = get_norm(+ op.sub(self.target_mobject.get_right(), self.starting_mobject.get_right(),)+ )if not self.moving_forward:distance *= -1tire_radius = car.get_tires()[0].get_width() / 2@@ -65,20 +64,11 @@ class Broadcast(LaggedStart):digest_config(self, kwargs)circles = VGroup()for x in range(self.n_circles):- circle = Circle(- radius=self.big_radius,- stroke_color=BLACK,- stroke_width=0,- )- circle.add_updater(- lambda c: c.move_to(focal_point)- )+ circle = Circle(radius=self.big_radius, stroke_color=BLACK, stroke_width=0,)+ circle.add_updater(lambda c: c.move_to(focal_point))circle.save_state()circle.set_width(self.small_radius * 2)circle.set_stroke(self.color, self.start_stroke_width)circles.add(circle)- animations = [- Restore(circle)- for circle in circles- ]- super().__init__(*animations, **kwargs)\ No newline at end of file+ animations = [Restore(circle) for circle in circles]+ super().__init__(*animations, **kwargs)diff --git a/manim/animation/transform.py b/manim/animation/transform.pyindex 37aa5bcf8..6c01e5690 100644--- a/manim/animation/transform.py+++ b/manim/animation/transform.py@@ -34,10 +34,7 @@ class Transform(Animation):elif self.path_arc == 0:self.path_func = straight_pathelse:- self.path_func = path_along_arc(- self.path_arc,- self.path_arc_axis,- )+ self.path_func = path_along_arc(self.path_arc, self.path_arc_axis,)def begin(self):# Use a copy of target_mobject for the align_data@@ -59,9 +56,7 @@ class Transform(Animation):def check_target_mobject_validity(self):if self.target_mobject is None:message = "{}.create_target not properly implemented"- raise Exception(- message.format(self.__class__.__name__)- )+ raise Exception(message.format(self.__class__.__name__))def clean_up_from_scene(self, scene):super().clean_up_from_scene(scene)@@ -73,8 +68,7 @@ class Transform(Animation):Animation.update_config(self, **kwargs)if "path_arc" in kwargs:self.path_func = path_along_arc(- kwargs["path_arc"],- kwargs.get("path_arc_axis", OUT)+ kwargs["path_arc"], kwargs.get("path_arc_axis", OUT))def get_all_mobjects(self):@@ -86,20 +80,15 @@ class Transform(Animation):]def get_all_families_zipped(self):- return zip(*[- mob.family_members_with_points()- for mob in [- self.mobject,- self.starting_mobject,- self.target_copy,+ return zip(+ *[+ mob.family_members_with_points()+ for mob in [self.mobject, self.starting_mobject, self.target_copy,]]- ])+ )def interpolate_submobject(self, submob, start, target_copy, alpha):- submob.interpolate(- start, target_copy,- alpha, self.path_func- )+ submob.interpolate(start, target_copy, alpha, self.path_func)return self@@ -122,15 +111,11 @@ class TransformFromCopy(Transform):class ClockwiseTransform(Transform):- CONFIG = {- "path_arc": -np.pi- }+ CONFIG = {"path_arc": -np.pi}class CounterclockwiseTransform(Transform):- CONFIG = {- "path_arc": np.pi- }+ CONFIG = {"path_arc": np.pi}class MoveToTarget(Transform):@@ -141,8 +126,7 @@ class MoveToTarget(Transform):def check_validity_of_input(self, mobject):if not hasattr(mobject, "target"):raise Exception(- "MoveToTarget called on mobject"- "without attribute 'target'"+ "MoveToTarget called on mobject" "without attribute 'target'")@@ -167,7 +151,7 @@ class ApplyMethod(Transform):"Whoops, looks like you accidentally invoked ""the method you want to animate")- assert(isinstance(method.__self__, Mobject))+ assert isinstance(method.__self__, Mobject)def create_target(self):method = self.method@@ -184,9 +168,7 @@ class ApplyMethod(Transform):class ApplyPointwiseFunction(ApplyMethod):- CONFIG = {- "run_time": DEFAULT_POINTWISE_FUNCTION_RUN_TIME- }+ CONFIG = {"run_time": DEFAULT_POINTWISE_FUNCTION_RUN_TIME}def __init__(self, function, mobject, **kwargs):super().__init__(mobject.apply_function, function, **kwargs)@@ -198,9 +180,7 @@ class ApplyPointwiseFunctionToCenter(ApplyPointwiseFunction):super().__init__(mobject.move_to, **kwargs)def begin(self):- self.method_args = [- self.function(self.mobject.get_center())- ]+ self.method_args = [self.function(self.mobject.get_center())]super().begin()@@ -232,7 +212,9 @@ class ApplyFunction(Transform):def create_target(self):target = self.function(self.mobject.copy())if not isinstance(target, Mobject):- raise Exception("Functions passed to ApplyFunction must return object of type Mobject")+ raise Exception(+ "Functions passed to ApplyFunction must return object of type Mobject"+ )return target@@ -267,6 +249,7 @@ class ApplyComplexFunction(ApplyMethod):self.path_arc = np.log(func1).imagsuper().init_path_func()+###@@ -293,9 +276,7 @@ class Swap(CyclicReplace):# TODO, this may be depricated...worth reimplementing?class TransformAnimations(Transform):- CONFIG = {- "rate_func": squish_rate_func(smooth)- }+ CONFIG = {"rate_func": squish_rate_func(smooth)}def __init__(self, start_anim, end_anim, **kwargs):digest_config(self, kwargs, locals())@@ -306,14 +287,16 @@ class TransformAnimations(Transform):for anim in start_anim, end_anim:anim.set_run_time(self.run_time)- if start_anim.starting_mobject.get_num_points() != end_anim.starting_mobject.get_num_points():+ if (+ start_anim.starting_mobject.get_num_points()+ != end_anim.starting_mobject.get_num_points()+ ):start_anim.starting_mobject.align_data(end_anim.starting_mobject)for anim in start_anim, end_anim:if hasattr(anim, "target_mobject"):anim.starting_mobject.align_data(anim.target_mobject)- Transform.__init__(self, start_anim.mobject,- end_anim.mobject, **kwargs)+ Transform.__init__(self, start_anim.mobject, end_anim.mobject, **kwargs)# Rewire starting and ending mobjectsstart_anim.mobject = self.starting_mobjectend_anim.mobject = self.target_mobjectdiff --git a/manim/animation/update.py b/manim/animation/update.pyindex 471707629..4166cc3fb 100644--- a/manim/animation/update.py+++ b/manim/animation/update.py@@ -9,6 +9,7 @@ class UpdateFromFunc(Animation):to be used when the state of one mobject is dependenton another simultaneously animated mobject"""+CONFIG = {"suspend_mobject_updating": False,}@@ -29,13 +30,10 @@ class UpdateFromAlphaFunc(UpdateFromFunc):class MaintainPositionRelativeTo(Animation):def __init__(self, mobject, tracked_mobject, **kwargs):self.tracked_mobject = tracked_mobject- self.diff = op.sub(- mobject.get_center(),- tracked_mobject.get_center(),- )+ self.diff = op.sub(mobject.get_center(), tracked_mobject.get_center(),)super().__init__(mobject, **kwargs)def interpolate_mobject(self, alpha):target = self.tracked_mobject.get_center()location = self.mobject.get_center()- self.mobject.shift(target - location + self.diff)\ No newline at end of file+ self.mobject.shift(target - location + self.diff)diff --git a/manim/camera/camera.py b/manim/camera/camera.pyindex bb0145bca..e5b4b03a7 100644--- a/manim/camera/camera.py+++ b/manim/camera/camera.py@@ -26,6 +26,7 @@ from ..utils.simple_functions import fdivfrom ..utils.space_ops import angle_of_vectorfrom ..utils.space_ops import get_norm+class Camera(object):"""Base Camera class.@@ -40,24 +41,25 @@ class Camera(object):self.pixel_height"""+CONFIG = {"background_image": None,- "pixel_height": config['pixel_height'],- "pixel_width": config['pixel_width'],- "frame_rate": config['frame_rate'],+ "pixel_height": config["pixel_height"],+ "pixel_width": config["pixel_width"],+ "frame_rate": config["frame_rate"],# Note: frame height and width will be resized to match# the pixel aspect ratio- "frame_height": config['frame_height'],- "frame_width": config['frame_width'],+ "frame_height": config["frame_height"],+ "frame_width": config["frame_width"],"frame_center": ORIGIN,"background_color": BLACK,"background_opacity": 1,# Points in vectorized mobjects with norm greater# than this value will be rescaled.- "max_allowable_norm": config['frame_width'],+ "max_allowable_norm": config["frame_width"],"image_mode": "RGBA","n_channels": 4,- "pixel_array_dtype": 'uint8',+ "pixel_array_dtype": "uint8",# z_buff_func is only used if the flag above is set to True.# round z coordinate to nearest hundredth when comparring"z_buff_func": lambda m: np.round(m.get_center()[2], 2),@@ -237,8 +239,7 @@ class Camera(object):self.background_color, self.background_opacity)self.background = np.zeros(- (height, width, self.n_channels),- dtype=self.pixel_array_dtype+ (height, width, self.n_channels), dtype=self.pixel_array_dtype)self.background[:, :] = background_rgba@@ -259,10 +260,7 @@ class Camera(object):"""if pixel_array is None:pixel_array = self.pixel_array- return Image.fromarray(- pixel_array,- mode=self.image_mode- )+ return Image.fromarray(pixel_array, mode=self.image_mode)def get_pixel_array(self):"""Returns the pixel array@@ -296,7 +294,7 @@ class Camera(object):retval = np.apply_along_axis(lambda f: (f * self.rgb_max_val).astype(self.pixel_array_dtype),2,- retval+ retval,)return retval@@ -310,9 +308,11 @@ class Camera(object):convert_from_floats : bool, optionalWhether or not to convert float values to proper RGB values, by default False"""- converted_array = self.convert_pixel_array(- pixel_array, convert_from_floats)- if not (hasattr(self, "pixel_array") and self.pixel_array.shape == converted_array.shape):+ converted_array = self.convert_pixel_array(pixel_array, convert_from_floats)+ if not (+ hasattr(self, "pixel_array")+ and self.pixel_array.shape == converted_array.shape+ ):self.pixel_array = converted_arrayelse:# Set in place@@ -329,8 +329,7 @@ class Camera(object):convert_from_floats : bool, optionalWhether or not to convert floats values to proper RGB valid ones, by default False"""- self.background = self.convert_pixel_array(- pixel_array, convert_from_floats)+ self.background = self.convert_pixel_array(pixel_array, convert_from_floats)# TODO, this should live in utils, not as a method of Cameradef make_background_from_func(self, coords_to_colors_func):@@ -350,14 +349,16 @@ class Camera(object):The pixel array which can then be passed to set_background."""- logger.info("Starting set_background; for reference, the current time is ", time.strftime("%H:%M:%S"))+ logger.info(+ "Starting set_background; for reference, the current time is ",+ time.strftime("%H:%M:%S"),+ )coords = self.get_coords_of_all_pixels()- new_background = np.apply_along_axis(- coords_to_colors_func,- 2,- coords+ new_background = np.apply_along_axis(coords_to_colors_func, 2, coords)+ logger.info(+ "Ending set_background; for reference, the current time is ",+ time.strftime("%H:%M:%S"),)- logger.info("Ending set_background; for reference, the current time is ", time.strftime("%H:%M:%S"))return self.convert_pixel_array(new_background, convert_from_floats=True)@@ -373,8 +374,7 @@ class Camera(object):The function whose input is an (x,y) pair of coordinats andwhose return values must be the colors for that point"""- self.set_background(- self.make_background_from_func(coords_to_colors_func))+ self.set_background(self.make_background_from_func(coords_to_colors_func))def reset(self):"""Resets the camera's pixel array@@ -384,7 +384,7 @@ class Camera(object):-------CameraThe camera object after setting the pixel array.- """""+ """ ""self.set_pixel_array(self.background)return self@@ -392,9 +392,7 @@ class Camera(object):# TODO, it's weird that this is part of camera.# Clearly it should live elsewhere.- def extract_mobject_family_members(- self, mobjects,- only_those_with_points=False):+ def extract_mobject_family_members(self, mobjects, only_those_with_points=False):"""Returns a list of the types of mobjects andtheir family members present.@@ -417,14 +415,11 @@ class Camera(object):method = Mobject.get_familyif self.use_z_index:mobjects.sort(key=lambda m: m.z_index)- return remove_list_redundancies(list(- it.chain(*[method(m) for m in mobjects])- ))+ return remove_list_redundancies(list(it.chain(*[method(m) for m in mobjects])))def get_mobjects_to_display(- self, mobjects,- include_submobjects=True,- excluded_mobjects=None):+ self, mobjects, include_submobjects=True, excluded_mobjects=None+ ):"""Used to get the list of mobjects to displaywith the camera.@@ -447,9 +442,7 @@ class Camera(object):mobjects, only_those_with_points=True,)if excluded_mobjects:- all_excluded = self.extract_mobject_family_members(- excluded_mobjects- )+ all_excluded = self.extract_mobject_family_members(excluded_mobjects)mobjects = list_difference_update(mobjects, all_excluded)return mobjects@@ -470,17 +463,24 @@ class Camera(object):fc = self.get_frame_center()fh = self.get_frame_height()fw = self.get_frame_width()- return not reduce(op.or_, [- mobject.get_right()[0] < fc[0] - fw,- mobject.get_bottom()[1] > fc[1] + fh,- mobject.get_left()[0] > fc[0] + fw,- mobject.get_top()[1] < fc[1] - fh,- ])-- def capture_mobject(self, mobject, **kwargs): #TODO Write better docstrings for this method.+ return not reduce(+ op.or_,+ [+ mobject.get_right()[0] < fc[0] - fw,+ mobject.get_bottom()[1] > fc[1] + fh,+ mobject.get_left()[0] > fc[0] + fw,+ mobject.get_top()[1] < fc[1] - fh,+ ],+ )++ def capture_mobject(+ self, mobject, **kwargs+ ): # TODO Write better docstrings for this method.return self.capture_mobjects([mobject], **kwargs)- def capture_mobjects(self, mobjects, **kwargs): #TODO Write better docstrings for this method.+ def capture_mobjects(+ self, mobjects, **kwargs+ ): # TODO Write better docstrings for this method.mobjects = self.get_mobjects_to_display(mobjects, **kwargs)# Organize this list into batches of the same type, and@@ -496,9 +496,8 @@ class Camera(object):for mobject_type, func in type_func_pairs:if isinstance(mobject, mobject_type):return mobject_type- raise Exception(- "Trying to display something which is not of type Mobject"- )+ raise Exception("Trying to display something which is not of type Mobject")+batch_type_pairs = batch_by_property(mobjects, get_mobject_type)# Display in these batches@@ -527,9 +526,7 @@ class Camera(object):Cairo.Context.ContextThe cached cairo context."""- return self.pixel_array_to_cairo_context.get(- id(pixel_array), None- )+ return self.pixel_array_to_cairo_context.get(id(pixel_array), None)def cache_cairo_context(self, pixel_array, ctx):"""Caches the passed Pixel array into a Cairo Context@@ -568,18 +565,20 @@ class Camera(object):fh = self.get_frame_height()fc = self.get_frame_center()surface = cairo.ImageSurface.create_for_data(- pixel_array,- cairo.FORMAT_ARGB32,- pw, ph+ pixel_array, cairo.FORMAT_ARGB32, pw, ph)ctx = cairo.Context(surface)ctx.scale(pw, ph)- ctx.set_matrix(cairo.Matrix(- fdiv(pw, fw), 0,- 0, -fdiv(ph, fh),- (pw / 2) - fc[0] * fdiv(pw, fw),- (ph / 2) + fc[1] * fdiv(ph, fh),- ))+ ctx.set_matrix(+ cairo.Matrix(+ fdiv(pw, fw),+ 0,+ 0,+ -fdiv(ph, fh),+ (pw / 2) - fc[0] * fdiv(pw, fw),+ (ph / 2) + fc[1] * fdiv(ph, fh),+ )+ )self.cache_cairo_context(pixel_array, ctx)return ctx@@ -596,14 +595,15 @@ class Camera(object):if len(vmobjects) == 0:returnbatch_file_pairs = batch_by_property(- vmobjects,- lambda vm: vm.get_background_image_file()+ vmobjects, lambda vm: vm.get_background_image_file())for batch, file_name in batch_file_pairs:if file_name:self.display_multiple_background_colored_vmobject(batch, pixel_array)else:- self.display_multiple_non_background_colored_vmobjects(batch, pixel_array)+ self.display_multiple_non_background_colored_vmobjects(+ batch, pixel_array+ )def display_multiple_non_background_colored_vmobjects(self, vmobjects, pixel_array):"""Displays multiple VMobjects in the cairo context, as long as they don't have@@ -656,9 +656,7 @@ class Camera(object):CameraCamera object after setting cairo_context_path"""- points = self.transform_points_pre_display(- vmobject, vmobject.points- )+ points = self.transform_points_pre_display(vmobject, vmobject.points)# TODO, shouldn't this be handled in transform_points_pre_display?# points = points - self.get_frame_center()if len(points) == 0:@@ -697,23 +695,15 @@ class Camera(object):if len(rgbas) == 1:# Use reversed rgb because cairo surface is# encodes it in reverse order- ctx.set_source_rgba(- *rgbas[0][2::-1], rgbas[0][3]- )+ ctx.set_source_rgba(*rgbas[0][2::-1], rgbas[0][3])else:points = vmobject.get_gradient_start_and_end_points()- points = self.transform_points_pre_display(- vmobject, points- )- pat = cairo.LinearGradient(*it.chain(*[- point[:2] for point in points- ]))+ points = self.transform_points_pre_display(vmobject, points)+ pat = cairo.LinearGradient(*it.chain(*[point[:2] for point in points]))step = 1.0 / (len(rgbas) - 1)offsets = np.arange(0, 1 + step, step)for rgba, offset in zip(rgbas, offsets):- pat.add_color_stop_rgba(- offset, *rgba[2::-1], rgba[3]- )+ pat.add_color_stop_rgba(offset, *rgba[2::-1], rgba[3])ctx.set_source(pat)return self@@ -732,9 +722,7 @@ class Camera(object):CameraThe camera object."""- self.set_cairo_context_color(- ctx, self.get_fill_rgbas(vmobject), vmobject- )+ self.set_cairo_context_color(ctx, self.get_fill_rgbas(vmobject), vmobject)ctx.fill_preserve()return self@@ -760,12 +748,12 @@ class Camera(object):if width == 0:return selfself.set_cairo_context_color(- ctx,- self.get_stroke_rgbas(vmobject, background=background),- vmobject+ ctx, self.get_stroke_rgbas(vmobject, background=background), vmobject)ctx.set_line_width(- width * self.cairo_line_width_multiple *+ width+ * self.cairo_line_width_multiple+ *# This ensures lines have constant width# as you zoom in on them.(self.get_frame_width() / self.frame_width)@@ -885,12 +873,8 @@ class Camera(object):"""if len(points) == 0:return- pixel_coords = self.points_to_pixel_coords(- pmobject, points- )- pixel_coords = self.thickened_coordinates(- pixel_coords, thickness- )+ pixel_coords = self.points_to_pixel_coords(pmobject, points)+ pixel_coords = self.thickened_coordinates(pixel_coords, thickness)rgba_len = pixel_array.shape[2]rgbas = (self.rgb_max_val * rgbas).astype(self.pixel_array_dtype)@@ -905,10 +889,10 @@ class Camera(object):ph = self.get_pixel_height()pw = self.get_pixel_width()- flattener = np.array([1, pw], dtype='int')+ flattener = np.array([1, pw], dtype="int")flattener = flattener.reshape((2, 1))indices = np.dot(pixel_coords, flattener)[:, 0]- indices = indices.astype('int')+ indices = indices.astype("int")new_pa = pixel_array.reshape((ph * pw, rgba_len))new_pa[indices] = rgbas@@ -937,18 +921,13 @@ class Camera(object):pixel_array : np.ndarrayThe Pixel array to put the imagemobject in."""- corner_coords = self.points_to_pixel_coords(- image_mobject, image_mobject.points- )+ corner_coords = self.points_to_pixel_coords(image_mobject, image_mobject.points)ul_coords, ur_coords, dl_coords = corner_coordsright_vect = ur_coords - ul_coordsdown_vect = dl_coords - ul_coordscenter_coords = ul_coords + (right_vect + down_vect) / 2- sub_image = Image.fromarray(- image_mobject.get_pixel_array(),- mode="RGBA"- )+ sub_image = Image.fromarray(image_mobject.get_pixel_array(), mode="RGBA")# Reshapepixel_width = max(int(pdist([ul_coords, ur_coords])), 1)@@ -969,8 +948,7 @@ class Camera(object):# Paste into an image as large as the camear's pixel arrayfull_image = Image.fromarray(- np.zeros((self.get_pixel_height(), self.get_pixel_width())),- mode="RGBA"+ np.zeros((self.get_pixel_height(), self.get_pixel_width())), mode="RGBA")new_ul_coords = center_coords - np.array(sub_image.size) / 2new_ul_coords = new_ul_coords.astype(int)@@ -981,7 +959,7 @@ class Camera(object):new_ul_coords[1],new_ul_coords[0] + sub_image.size[0],new_ul_coords[1] + sub_image.size[1],- )+ ),)# Paint on top of existing pixel arrayself.overlay_PIL_image(pixel_array, full_image)@@ -997,8 +975,7 @@ class Camera(object):The new pixel array to overlay."""self.overlay_PIL_image(- pixel_array,- self.get_image(new_array),+ pixel_array, self.get_image(new_array),)def overlay_PIL_image(self, pixel_array, image):@@ -1012,11 +989,7 @@ class Camera(object):The Image to overlay."""pixel_array[:, :] = np.array(- Image.alpha_composite(- self.get_image(pixel_array),- image- ),- dtype='uint8'+ Image.alpha_composite(self.get_image(pixel_array), image), dtype="uint8")def adjust_out_of_range_points(self, points):@@ -1040,15 +1013,16 @@ class Camera(object):violators = points[violator_indices, :]violator_norms = norms[violator_indices]reshaped_norms = np.repeat(- violator_norms.reshape((len(violator_norms), 1)),- points.shape[1], 1+ violator_norms.reshape((len(violator_norms), 1)), points.shape[1], 1)rescaled = self.max_allowable_norm * violators / reshaped_normspoints[violator_indices] = rescaledreturn points- def transform_points_pre_display(self, mobject, points): #TODO: Write more detailed docstrings for this method.- #NOTE: There seems to be an unused argument `mobject`.+ def transform_points_pre_display(+ self, mobject, points+ ): # TODO: Write more detailed docstrings for this method.+ # NOTE: There seems to be an unused argument `mobject`.# Subclasses (like ThreeDCamera) may want to# adjust points futher before they're shown@@ -1058,10 +1032,10 @@ class Camera(object):points = np.zeros((1, 3))return points- def points_to_pixel_coords(self, mobject, points): #TODO: Write more detailed docstrings for this method.- points = self.transform_points_pre_display(- mobject, points- )+ def points_to_pixel_coords(+ self, mobject, points+ ): # TODO: Write more detailed docstrings for this method.+ points = self.transform_points_pre_display(mobject, points)shifted_points = points - self.get_frame_center()result = np.zeros((len(points), 2))@@ -1078,7 +1052,7 @@ class Camera(object):result[:, 0] = shifted_points[:, 0] * width_mult + width_addresult[:, 1] = shifted_points[:, 1] * height_mult + height_add- return result.astype('int')+ return result.astype("int")def on_screen_pixels(self, pixel_coords):"""Returns array of pixels that are on the screen from a given@@ -1094,12 +1068,15 @@ class Camera(object):np.arrayThe pixel coords on screen."""- return reduce(op.and_, [- pixel_coords[:, 0] >= 0,- pixel_coords[:, 0] < self.get_pixel_width(),- pixel_coords[:, 1] >= 0,- pixel_coords[:, 1] < self.get_pixel_height(),- ])+ return reduce(+ op.and_,+ [+ pixel_coords[:, 0] >= 0,+ pixel_coords[:, 0] < self.get_pixel_width(),+ pixel_coords[:, 1] >= 0,+ pixel_coords[:, 1] < self.get_pixel_height(),+ ],+ )def adjusted_thickness(self, thickness):"""@@ -1118,10 +1095,7 @@ class Camera(object):PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_height"],PRODUCTION_QUALITY_CAMERA_CONFIG["pixel_width"],)- this_sum = op.add(- self.get_pixel_height(),- self.get_pixel_width(),- )+ this_sum = op.add(self.get_pixel_height(), self.get_pixel_width(),)factor = fdiv(big_sum, this_sum)return 1 + (thickness - 1) / factor@@ -1158,10 +1132,7 @@ class Camera(object):Array of thickened pixel coords."""nudges = self.get_thickening_nudges(thickness)- pixel_coords = np.array([- pixel_coords + nudge- for nudge in nudges- ])+ pixel_coords = np.array([pixel_coords + nudge for nudge in nudges])size = pixel_coords.sizereturn pixel_coords.reshape((size // 2, 2))@@ -1175,14 +1146,8 @@ class Camera(object):The array of cartesian coordinates."""# These are in x, y order, to help me keep things straight- full_space_dims = np.array([- self.get_frame_width(),- self.get_frame_height()- ])- full_pixel_dims = np.array([- self.get_pixel_width(),- self.get_pixel_height()- ])+ full_space_dims = np.array([self.get_frame_width(), self.get_frame_height()])+ full_pixel_dims = np.array([self.get_pixel_width(), self.get_pixel_height()])# These are addressed in the same y, x order as in pixel_array, but the values in them# are listed in x, y order@@ -1190,16 +1155,14 @@ class Camera(object):[self.get_pixel_height(), self.get_pixel_width()])[::-1].transpose(1, 2, 0)uncentered_space_coords = fdiv(- uncentered_pixel_coords * full_space_dims,- full_pixel_dims)+ uncentered_pixel_coords * full_space_dims, full_pixel_dims+ )# Could structure above line's computation slightly differently, but figured (without much# thought) multiplying by frame_shape first, THEN dividing by pixel_shape, is probably# better than the other order, for avoiding underflow quantization in the division (whereas# overflow is unlikely to be a problem)- centered_space_coords = (- uncentered_space_coords - fdiv(full_space_dims, 2)- )+ centered_space_coords = uncentered_space_coords - fdiv(full_space_dims, 2)# Have to also flip the y coordinates to account for pixel array being listed in# top-to-bottom order, opposite of screen coordinate convention@@ -1207,6 +1170,7 @@ class Camera(object):return centered_space_coords+# NOTE: The methods of the following class have not been mentioned outside of their definitons.# Their DocStrings are not as detailed as preferred.class BackgroundColoredVMobjectDisplayer(object):@@ -1226,9 +1190,7 @@ class BackgroundColoredVMobjectDisplayer(object):self.pixel_array[:, :] = 0def resize_background_array(- self, background_array,- new_width, new_height,- mode="RGBA"+ self, background_array, new_width, new_height, mode="RGBA"):"""Resizes the pixel array represinting the background.@@ -1293,9 +1255,7 @@ class BackgroundColoredVMobjectDisplayer(object):pixel_array = self.pixel_arrayif not np.all(pixel_array.shape == back_array.shape):- back_array = self.resize_background_array_to_match(- back_array, pixel_array- )+ back_array = self.resize_background_array_to_match(back_array, pixel_array)self.file_name_to_pixel_array_map[file_name] = back_arrayreturn back_array@@ -1324,8 +1284,8 @@ class BackgroundColoredVMobjectDisplayer(object):batch, pixel_array)new_array = np.array(- (background_array * pixel_array.astype('float') / 255),- dtype=self.camera.pixel_array_dtype+ (background_array * pixel_array.astype("float") / 255),+ dtype=self.camera.pixel_array_dtype,)if curr_array is None:curr_array = new_arraydiff --git a/manim/camera/mapping_camera.py b/manim/camera/mapping_camera.pyindex 16ed82a64..f86d612cc 100644--- a/manim/camera/mapping_camera.py+++ b/manim/camera/mapping_camera.py@@ -13,14 +13,17 @@ class MappingCamera(Camera):"""Camera object that allows mappingbetween objects."""+CONFIG = {"mapping_func": lambda p: p,"min_num_curves": 50,- "allow_object_intrusion": False+ "allow_object_intrusion": False,}def points_to_pixel_coords(self, points):- return Camera.points_to_pixel_coords(self, np.apply_along_axis(self.mapping_func, 1, points))+ return Camera.points_to_pixel_coords(+ self, np.apply_along_axis(self.mapping_func, 1, points)+ )def capture_mobjects(self, mobjects, **kwargs):mobjects = self.get_mobjects_to_display(mobjects, **kwargs)@@ -29,13 +32,13 @@ class MappingCamera(Camera):else:mobject_copies = [mobject.copy() for mobject in mobjects]for mobject in mobject_copies:- if isinstance(mobject, VMobject) and \- 0 < mobject.get_num_curves() < self.min_num_curves:+ if (+ isinstance(mobject, VMobject)+ and 0 < mobject.get_num_curves() < self.min_num_curves+ ):mobject.insert_n_curves(self.min_num_curves)Camera.capture_mobjects(- self, mobject_copies,- include_submobjects=False,- excluded_mobjects=None,+ self, mobject_copies, include_submobjects=False, excluded_mobjects=None,)@@ -54,9 +57,12 @@ class OldMultiCamera(Camera):"camera": camera_with_start_positions[0],"start_x": camera_with_start_positions[1][1],"start_y": camera_with_start_positions[1][0],- "end_x": camera_with_start_positions[1][1] + camera_with_start_positions[0].get_pixel_width(),- "end_y": camera_with_start_positions[1][0] + camera_with_start_positions[0].get_pixel_height(),- })+ "end_x": camera_with_start_positions[1][1]+ + camera_with_start_positions[0].get_pixel_width(),+ "end_y": camera_with_start_positions[1][0]+ + camera_with_start_positions[0].get_pixel_height(),+ }+ )for camera_with_start_positions in cameras_with_start_positions]Camera.__init__(self, **kwargs)@@ -66,17 +72,18 @@ class OldMultiCamera(Camera):shifted_camera.camera.capture_mobjects(mobjects, **kwargs)self.pixel_array[- shifted_camera.start_y:shifted_camera.end_y,- shifted_camera.start_x:shifted_camera.end_x] \- = shifted_camera.camera.pixel_array+ shifted_camera.start_y : shifted_camera.end_y,+ shifted_camera.start_x : shifted_camera.end_x,+ ] = shifted_camera.camera.pixel_arraydef set_background(self, pixel_array, **kwargs):for shifted_camera in self.shifted_cameras:shifted_camera.camera.set_background(pixel_array[- shifted_camera.start_y:shifted_camera.end_y,- shifted_camera.start_x:shifted_camera.end_x],- **kwargs+ shifted_camera.start_y : shifted_camera.end_y,+ shifted_camera.start_x : shifted_camera.end_x,+ ],+ **kwargs,)def set_pixel_array(self, pixel_array, **kwargs):@@ -84,9 +91,10 @@ class OldMultiCamera(Camera):for shifted_camera in self.shifted_cameras:shifted_camera.camera.set_pixel_array(pixel_array[- shifted_camera.start_y:shifted_camera.end_y,- shifted_camera.start_x:shifted_camera.end_x],- **kwargs+ shifted_camera.start_y : shifted_camera.end_y,+ shifted_camera.start_x : shifted_camera.end_x,+ ],+ **kwargs,)def init_background(self):@@ -94,6 +102,7 @@ class OldMultiCamera(Camera):for shifted_camera in self.shifted_cameras:shifted_camera.camera.init_background()+# A OldMultiCamera which, when called with two full-size cameras, initializes itself# as a splitscreen, also taking care to resize each individual camera within it@@ -110,7 +119,5 @@ class SplitScreenCamera(OldMultiCamera):camera.reset_pixel_shape(camera.get_pixel_height(), half_width)OldMultiCamera.__init__(- self,- (left_camera, (0, 0)),- (right_camera, (0, half_width)),- )\ No newline at end of file+ self, (left_camera, (0, 0)), (right_camera, (0, half_width)),+ )diff --git a/manim/camera/moving_camera.py b/manim/camera/moving_camera.pyindex f7e84986f..253498c76 100644--- a/manim/camera/moving_camera.py+++ b/manim/camera/moving_camera.py@@ -9,8 +9,8 @@ from ..utils.config_ops import digest_config# TODO, think about how to incorporate perspectiveclass CameraFrame(VGroup):CONFIG = {- "width": config['frame_width'],- "height": config['frame_height'],+ "width": config["frame_width"],+ "height": config["frame_height"],"center": ORIGIN,}@@ -36,10 +36,9 @@ class MovingCamera(Camera):"""digest_config(self, kwargs)if frame is None:- frame = ScreenRectangle(height=config['frame_height'])+ frame = ScreenRectangle(height=config["frame_height"])frame.set_stroke(- self.default_frame_stroke_color,- self.default_frame_stroke_width,+ self.default_frame_stroke_color, self.default_frame_stroke_width,)self.frame = frameCamera.__init__(self, **kwargs)diff --git a/manim/camera/multi_camera.py b/manim/camera/multi_camera.pyindex 8e3ef108f..6065786d3 100644--- a/manim/camera/multi_camera.py+++ b/manim/camera/multi_camera.py@@ -5,6 +5,7 @@ from ..utils.iterables import list_difference_updateclass MultiCamera(MovingCamera):"""Camera Object that allows for multiple perspectives."""+CONFIG = {"allow_cameras_to_capture_their_own_display": False,}@@ -36,7 +37,7 @@ class MultiCamera(MovingCamera):# A silly method to have right now, but maybe there are things# we want to guarantee about any imfc's added later.imfc = image_mobject_from_camera- assert(isinstance(imfc.camera, MovingCamera))+ assert isinstance(imfc.camera, MovingCamera)self.image_mobjects_from_cameras.append(imfc)def update_sub_cameras(self):@@ -70,9 +71,7 @@ class MultiCamera(MovingCamera):for imfc in self.image_mobjects_from_cameras:to_add = list(mobjects)if not self.allow_cameras_to_capture_their_own_display:- to_add = list_difference_update(- to_add, imfc.get_family()- )+ to_add = list_difference_update(to_add, imfc.get_family())imfc.camera.capture_mobjects(to_add, **kwargs)MovingCamera.capture_mobjects(self, mobjects, **kwargs)@@ -85,6 +84,5 @@ class MultiCamera(MovingCamera):list"""return [self.frame] + [- imfc.camera.frame- for imfc in self.image_mobjects_from_cameras- ]\ No newline at end of file+ imfc.camera.frame for imfc in self.image_mobjects_from_cameras+ ]diff --git a/manim/camera/three_d_camera.py b/manim/camera/three_d_camera.pyindex 339555c3a..79b3f908a 100644--- a/manim/camera/three_d_camera.py+++ b/manim/camera/three_d_camera.py@@ -27,7 +27,7 @@ class ThreeDCamera(Camera):"frame_center": ORIGIN,"should_apply_shading": True,"exponential_projection": False,- "max_allowable_norm": 3 * config['frame_width'],+ "max_allowable_norm": 3 * config["frame_width"],}def __init__(self, *args, **kwargs):@@ -70,7 +70,9 @@ class ThreeDCamera(Camera):self.gamma_tracker,]- def modified_rgbas(self, vmobject, rgbas): # TODO: Write DocStrings for this method.+ def modified_rgbas(+ self, vmobject, rgbas+ ): # TODO: Write DocStrings for this method.if not self.should_apply_shading:return rgbasif vmobject.shade_in_3d and (vmobject.get_num_points() > 0):@@ -94,20 +96,16 @@ class ThreeDCamera(Camera):return shaded_rgbasreturn rgbas- def get_stroke_rgbas(self, vmobject, background=False): #NOTE : DocStrings From parent- return self.modified_rgbas(- vmobject, vmobject.get_stroke_rgbas(background)- )+ def get_stroke_rgbas(+ self, vmobject, background=False+ ): # NOTE : DocStrings From parent+ return self.modified_rgbas(vmobject, vmobject.get_stroke_rgbas(background))- def get_fill_rgbas(self, vmobject): #NOTE : DocStrings From parent- return self.modified_rgbas(- vmobject, vmobject.get_fill_rgbas()- )+ def get_fill_rgbas(self, vmobject): # NOTE : DocStrings From parent+ return self.modified_rgbas(vmobject, vmobject.get_fill_rgbas())- def get_mobjects_to_display(self, *args, **kwargs): #NOTE : DocStrings From parent- mobjects = Camera.get_mobjects_to_display(- self, *args, **kwargs- )+ def get_mobjects_to_display(self, *args, **kwargs): # NOTE : DocStrings From parent+ mobjects = Camera.get_mobjects_to_display(self, *args, **kwargs)rot_matrix = self.get_rotation_matrix()def z_key(mob):@@ -115,10 +113,8 @@ class ThreeDCamera(Camera):return np.inf# Assign a number to a three dimensional mobjects# based on how close it is to the camera- return np.dot(- mob.get_z_index_reference_point(),- rot_matrix.T- )[2]+ return np.dot(mob.get_z_index_reference_point(), rot_matrix.T)[2]+return sorted(mobjects, key=z_key)def get_phi(self):@@ -288,10 +284,10 @@ class ThreeDCamera(Camera):# the exponential helps smooth it out.factor = np.exp(zs / distance)lt0 = zs < 0- factor[lt0] = (distance / (distance - zs[lt0]))+ factor[lt0] = distance / (distance - zs[lt0])else:- factor = (distance / (distance - zs))- factor[(distance - zs) < 0] = 10**6+ factor = distance / (distance - zs)+ factor[(distance - zs) < 0] = 10 ** 6# clip_in_place(factor, 0, 10**6)points[:, i] *= factorpoints = points + frame_center@@ -313,7 +309,9 @@ class ThreeDCamera(Camera):"""return self.project_points(point.reshape((1, 3)))[0, :]- def transform_points_pre_display(self, mobject, points): #TODO: Write Docstrings for this Method.+ def transform_points_pre_display(+ self, mobject, points+ ): # TODO: Write Docstrings for this Method.points = super().transform_points_pre_display(mobject, points)fixed_orientation = mobject in self.fixed_orientation_mobjectsfixed_in_frame = mobject in self.fixed_in_frame_mobjects@@ -329,9 +327,8 @@ class ThreeDCamera(Camera):return self.project_points(points)def add_fixed_orientation_mobjects(- self, *mobjects,- use_static_center_func=False,- center_func=None):+ self, *mobjects, use_static_center_func=False, center_func=None+ ):"""This method allows the mobject to have a fixed orientation,even when the camera moves around.E.G If it was passed through this method, facing the camera, it@@ -353,7 +350,7 @@ class ThreeDCamera(Camera):# every single time a projetion happensdef get_static_center_func(mobject):point = mobject.get_center()- return (lambda: point)+ return lambda: pointfor mobject in mobjects:if center_func:diff --git a/manim/config.py b/manim/config.pyindex 5ab17cabd..baec8299f 100644--- a/manim/config.py+++ b/manim/config.py@@ -79,9 +79,7 @@ def _parse_config(config_parser, args):tex_fn = Noneconfig["tex_template_file"] = tex_fnconfig["tex_template"] = (- TexTemplateFromFile(filename=tex_fn)- if tex_fn is not None- else TexTemplate()+ TexTemplateFromFile(filename=tex_fn) if tex_fn is not None else TexTemplate())return config@@ -89,7 +87,9 @@ def _parse_config(config_parser, args):args, config_parser, file_writer_config, successfully_read_files = _run_config()if _from_command_line():- logger.info(f"Read configuration files: {os.path.abspath(successfully_read_files[-1])}")+ logger.info(+ f"Read configuration files: {os.path.abspath(successfully_read_files[-1])}"+ )_init_dirs(file_writer_config)config = _parse_config(config_parser, args)camera_config = configdiff --git a/manim/constants.py b/manim/constants.pyindex e8acf30e6..e9f41a79f 100644--- a/manim/constants.py+++ b/manim/constants.py@@ -1,7 +1,7 @@import numpy as np# Messages-NOT_SETTING_FONT_MSG = '''+NOT_SETTING_FONT_MSG = """You haven't set font.If you are not using English, this may cause text rendering problem.You set font like:@@ -11,7 +11,7 @@ class MyText(Text):CONFIG = {'font': 'My Font'}-'''+"""SCENE_NOT_FOUND_MESSAGE = """{} is not in the script"""@@ -25,24 +25,24 @@ NO_SCENE_MESSAGE = """"""# Cairo stuff-NORMAL = 'NORMAL'-ITALIC = 'ITALIC'-OBLIQUE = 'OBLIQUE'-BOLD = 'BOLD'+NORMAL = "NORMAL"+ITALIC = "ITALIC"+OBLIQUE = "OBLIQUE"+BOLD = "BOLD"# Geometry: directions-ORIGIN = np.array((0., 0., 0.))-UP = np.array((0., 1., 0.))-DOWN = np.array((0., -1., 0.))-RIGHT = np.array((1., 0., 0.))-LEFT = np.array((-1., 0., 0.))-IN = np.array((0., 0., -1.))-OUT = np.array((0., 0., 1.))+ORIGIN = np.array((0.0, 0.0, 0.0))+UP = np.array((0.0, 1.0, 0.0))+DOWN = np.array((0.0, -1.0, 0.0))+RIGHT = np.array((1.0, 0.0, 0.0))+LEFT = np.array((-1.0, 0.0, 0.0))+IN = np.array((0.0, 0.0, -1.0))+OUT = np.array((0.0, 0.0, 1.0))# Geometry: axes-X_AXIS = np.array((1., 0., 0.))-Y_AXIS = np.array((0., 1., 0.))-Z_AXIS = np.array((0., 0., 1.))+X_AXIS = np.array((1.0, 0.0, 0.0))+Y_AXIS = np.array((0.0, 1.0, 0.0))+Z_AXIS = np.array((0.0, 0.0, 1.0))# Geometry: useful abbreviations for diagonalsUL = UP + LEFT@@ -80,7 +80,7 @@ DEGREES = TAU / 360FFMPEG_BIN = "ffmpeg"# gif stuff-GIF_FILE_EXTENSION = '.gif'+GIF_FILE_EXTENSION = ".gif"# ColorsCOLOR_MAP = {@@ -143,8 +143,12 @@ COLOR_MAP = {"GREEN_SCREEN": "#00FF00","ORANGE": "#FF862F",}-COLOR_MAP.update({name.replace("_C", ""): COLOR_MAP[name]- for name in COLOR_MAP- if name.endswith("_C")})+COLOR_MAP.update(+ {+ name.replace("_C", ""): COLOR_MAP[name]+ for name in COLOR_MAP+ if name.endswith("_C")+ }+)PALETTE = list(COLOR_MAP.values())locals().update(COLOR_MAP)diff --git a/manim/container/container.py b/manim/container/container.pyindex 8d84f2729..f986f1c40 100644--- a/manim/container/container.py+++ b/manim/container/container.py@@ -11,6 +11,7 @@ class Container(object):"""Base class for Scenes and Mobjects. Generic container."""+def __init__(self, **kwargs):digest_config(self, kwargs)@@ -20,7 +21,8 @@ class Container(object):Must be implemented by subclasses."""raise Exception(- "Container.add is not implemented; it is up to derived classes to implement")+ "Container.add is not implemented; it is up to derived classes to implement"+ )def remove(self, *items):"""@@ -28,4 +30,5 @@ class Container(object):Must be implemented by subclasses."""raise Exception(- "Container.remove is not implemented; it is up to derived classes to implement")+ "Container.remove is not implemented; it is up to derived classes to implement"+ )diff --git a/manim/mobject/changing.py b/manim/mobject/changing.pyindex f96ff1db5..02475d629 100644--- a/manim/mobject/changing.py+++ b/manim/mobject/changing.py@@ -19,17 +19,11 @@ class AnimatedBoundary(VGroup):super().__init__(**kwargs)self.vmobject = vmobjectself.boundary_copies = [- vmobject.copy().set_style(- stroke_width=0,- fill_opacity=0- )- for x in range(2)+ vmobject.copy().set_style(stroke_width=0, fill_opacity=0) for x in range(2)]self.add(*self.boundary_copies)self.total_time = 0- self.add_updater(- lambda m, dt: self.update_boundary_copies(dt)- )+ self.add_updater(lambda m, dt: self.update_boundary_copies(dt))def update_boundary_copies(self, dt):# Not actual time, but something which passes at@@ -55,10 +49,7 @@ class AnimatedBoundary(VGroup):if time >= 1:self.full_family_become_partial(fading, vmobject, 0, 1)- fading.set_stroke(- color=colors[index - 1],- width=(1 - fade_alpha) * msw- )+ fading.set_stroke(color=colors[index - 1], width=(1 - fade_alpha) * msw)self.total_time += dt@@ -95,4 +86,4 @@ class TracedPath(VMobject):nppcc = self.n_points_per_cubic_curvedist = get_norm(new_point - self.points[-nppcc])if dist >= self.min_distance_to_new_point:- self.add_line_to(new_point)\ No newline at end of file+ self.add_line_to(new_point)diff --git a/manim/mobject/coordinate_systems.py b/manim/mobject/coordinate_systems.pyindex 7ea66468e..713659f32 100644--- a/manim/mobject/coordinate_systems.py+++ b/manim/mobject/coordinate_systems.py@@ -17,16 +17,17 @@ from ..utils.space_ops import angle_of_vector# TODO: There should be much more code reuse between Axes, NumberPlane and GraphScene-class CoordinateSystem():+class CoordinateSystem:"""Abstract class for Axes and NumberPlane"""+CONFIG = {"dimension": 2,- "x_min": -config['frame_x_radius'],- "x_max": config['frame_x_radius'],- "y_min": -config['frame_y_radius'],- "y_max": config['frame_y_radius'],+ "x_min": -config["frame_x_radius"],+ "x_max": config["frame_x_radius"],+ "y_min": -config["frame_y_radius"],+ "y_max": config["frame_y_radius"],}def coords_to_point(self, *coords):@@ -60,29 +61,23 @@ class CoordinateSystem():def get_x_axis_label(self, label_tex, edge=RIGHT, direction=DL, **kwargs):return self.get_axis_label(- label_tex, self.get_x_axis(),- edge, direction, **kwargs+ label_tex, self.get_x_axis(), edge, direction, **kwargs)def get_y_axis_label(self, label_tex, edge=UP, direction=DR, **kwargs):return self.get_axis_label(- label_tex, self.get_y_axis(),- edge, direction, **kwargs+ label_tex, self.get_y_axis(), edge, direction, **kwargs)def get_axis_label(self, label_tex, axis, edge, direction, buff=MED_SMALL_BUFF):label = TexMobject(label_tex)- label.next_to(- axis.get_edge_center(edge), direction,- buff=buff- )+ label.next_to(axis.get_edge_center(edge), direction, buff=buff)label.shift_onto_screen(buff=MED_SMALL_BUFF)return labeldef get_axis_labels(self, x_label_tex="x", y_label_tex="y"):self.axis_labels = VGroup(- self.get_x_axis_label(x_label_tex),- self.get_y_axis_label(y_label_tex),+ self.get_x_axis_label(x_label_tex), self.get_y_axis_label(y_label_tex),)return self.axis_labels@@ -93,7 +88,7 @@ class CoordinateSystem():lambda t: self.coords_to_point(t, function(t)),t_min=x_min,t_max=x_max,- **kwargs+ **kwargs,)graph.underlying_function = functionreturn graph@@ -101,10 +96,7 @@ class CoordinateSystem():def get_parametric_curve(self, function, **kwargs):dim = self.dimensiongraph = ParametricFunction(- lambda t: self.coords_to_point(- *function(t)[:dim]- ),- **kwargs+ lambda t: self.coords_to_point(*function(t)[:dim]), **kwargs)graph.underlying_function = functionreturn graph@@ -114,9 +106,9 @@ class CoordinateSystem():return self.coords_to_point(x, graph.underlying_function(x))else:alpha = binary_search(- function=lambda a: self.point_to_coords(- graph.point_from_proportion(a)- )[0],+ function=lambda a: self.point_to_coords(graph.point_from_proportion(a))[+ 0+ ],target=x,lower_bound=self.x_min,upper_bound=self.x_max,@@ -135,20 +127,14 @@ class Axes(VGroup, CoordinateSystem):"exclude_zero_from_default_numbers": True,},"x_axis_config": {},- "y_axis_config": {- "label_direction": LEFT,- },+ "y_axis_config": {"label_direction": LEFT,},"center_point": ORIGIN,}def __init__(self, **kwargs):VGroup.__init__(self, **kwargs)- self.x_axis = self.create_axis(- self.x_min, self.x_max, self.x_axis_config- )- self.y_axis = self.create_axis(- self.y_min, self.y_max, self.y_axis_config- )+ self.x_axis = self.create_axis(self.x_min, self.x_max, self.x_axis_config)+ self.y_axis = self.create_axis(self.y_min, self.y_max, self.y_axis_config)self.y_axis.rotate(90 * DEGREES, about_point=ORIGIN)# Add as a separate group incase various other# mobjects are added to self, as for example in@@ -159,9 +145,7 @@ class Axes(VGroup, CoordinateSystem):def create_axis(self, min_val, max_val, axis_config):new_config = merge_dicts_recursively(- self.axis_config,- {"x_min": min_val, "x_max": max_val},- axis_config,+ self.axis_config, {"x_min": min_val, "x_max": max_val}, axis_config,)return NumberLine(**new_config)@@ -169,17 +153,14 @@ class Axes(VGroup, CoordinateSystem):origin = self.x_axis.number_to_point(0)result = np.array(origin)for axis, coord in zip(self.get_axes(), coords):- result += (axis.number_to_point(coord) - origin)+ result += axis.number_to_point(coord) - originreturn resultdef c2p(self, *coords):return self.coords_to_point(*coords)def point_to_coords(self, point):- return tuple([- axis.point_to_number(point)- for axis in self.get_axes()- ])+ return tuple([axis.point_to_number(point) for axis in self.get_axes()])def p2c(self, point):return self.point_to_coords(point)@@ -224,10 +205,7 @@ class ThreeDAxes(Axes):self.z_min, self.z_max, self.z_axis_config)z_axis.rotate(-np.pi / 2, UP, about_point=ORIGIN)- z_axis.rotate(- angle_of_vector(self.z_normal), OUT,- about_point=ORIGIN- )+ z_axis.rotate(angle_of_vector(self.z_normal), OUT, about_point=ORIGIN)self.axes.add(z_axis)self.add(z_axis)@@ -236,9 +214,7 @@ class ThreeDAxes(Axes):def add_3d_pieces(self):for axis in self.axes:- axis.pieces = VGroup(- *axis.get_pieces(self.num_axis_pieces)- )+ axis.pieces = VGroup(*axis.get_pieces(self.num_axis_pieces))axis.add(axis.pieces)axis.set_stroke(width=0, family=False)axis.set_shade_in_3d(True)@@ -246,10 +222,8 @@ class ThreeDAxes(Axes):def set_axis_shading(self):def make_func(axis):vect = self.light_source- return lambda: (- axis.get_edge_center(-vect),- axis.get_edge_center(vect),- )+ return lambda: (axis.get_edge_center(-vect), axis.get_edge_center(vect),)+for axis in self:for submob in axis.family_members_with_points():submob.get_gradient_start_and_end_points = make_func(axis)@@ -268,9 +242,7 @@ class NumberPlane(Axes):"label_direction": DR,"number_scale_val": 0.5,},- "y_axis_config": {- "label_direction": DR,- },+ "y_axis_config": {"label_direction": DR,},"background_line_style": {"stroke_color": BLUE_D,"stroke_width": 2,@@ -300,15 +272,10 @@ class NumberPlane(Axes):self.faded_line_style = styleself.background_lines, self.faded_lines = self.get_lines()- self.background_lines.set_style(- **self.background_line_style,- )- self.faded_lines.set_style(- **self.faded_line_style,- )+ self.background_lines.set_style(**self.background_line_style,)+ self.faded_lines.set_style(**self.faded_line_style,)self.add_to_back(- self.faded_lines,- self.background_lines,+ self.faded_lines, self.background_lines,)def get_lines(self):@@ -325,18 +292,18 @@ class NumberPlane(Axes):y_freq = self.y_line_frequencyx_lines1, x_lines2 = self.get_lines_parallel_to_axis(- x_axis, y_axis, x_freq,- self.faded_line_ratio,+ x_axis, y_axis, x_freq, self.faded_line_ratio,)y_lines1, y_lines2 = self.get_lines_parallel_to_axis(- y_axis, x_axis, y_freq,- self.faded_line_ratio,+ y_axis, x_axis, y_freq, self.faded_line_ratio,)lines1 = VGroup(*x_lines1, *y_lines1)lines2 = VGroup(*x_lines2, *y_lines2)return lines1, lines2- def get_lines_parallel_to_axis(self, axis_parallel_to, axis_perpendicular_to, freq, ratio_faded_lines):+ def get_lines_parallel_to_axis(+ self, axis_parallel_to, axis_perpendicular_to, freq, ratio_faded_lines+ ):"""Generate a set of lines parallel to an axis.Parameters@@ -393,18 +360,14 @@ class NumberPlane(Axes):def get_vector(self, coords, **kwargs):kwargs["buff"] = 0return Arrow(- self.coords_to_point(0, 0),- self.coords_to_point(*coords),- **kwargs+ self.coords_to_point(0, 0), self.coords_to_point(*coords), **kwargs)def prepare_for_nonlinear_transform(self, num_inserted_curves=50):for mob in self.family_members_with_points():num_curves = mob.get_num_curves()if num_inserted_curves > num_curves:- mob.insert_n_curves(- num_inserted_curves - num_curves- )+ mob.insert_n_curves(num_inserted_curves - num_curves)return self@@ -431,9 +394,7 @@ class ComplexPlane(NumberPlane):def get_default_coordinate_values(self):x_numbers = self.get_x_axis().default_numbers_to_display()y_numbers = self.get_y_axis().default_numbers_to_display()- y_numbers = [- complex(0, y) for y in y_numbers if y != 0- ]+ y_numbers = [complex(0, y) for y in y_numbers if y != 0]return [*x_numbers, *y_numbers]def get_coordinate_labels(self, *numbers, **kwargs):@@ -447,8 +408,7 @@ class ComplexPlane(NumberPlane):axis = self.get_y_axis()value = z.imagkwargs = merge_dicts_recursively(- kwargs,- {"number_config": {"unit": "i"}},+ kwargs, {"number_config": {"unit": "i"}},)else:axis = self.get_x_axis()diff --git a/manim/mobject/frame.py b/manim/mobject/frame.pyindex dfa096bd7..1c4b6e41b 100644--- a/manim/mobject/frame.py+++ b/manim/mobject/frame.py@@ -5,22 +5,16 @@ from ..utils.config_ops import digest_configclass ScreenRectangle(Rectangle):- CONFIG = {- "aspect_ratio": 16.0 / 9.0,- "height": 4- }+ CONFIG = {"aspect_ratio": 16.0 / 9.0, "height": 4}def __init__(self, **kwargs):Rectangle.__init__(self, **kwargs)- self.set_width(- self.aspect_ratio * self.get_height(),- stretch=True- )+ self.set_width(self.aspect_ratio * self.get_height(), stretch=True)class FullScreenRectangle(ScreenRectangle):CONFIG = {- "height": config['frame_height'],+ "height": config["frame_height"],}@@ -33,16 +27,10 @@ class FullScreenFadeRectangle(FullScreenRectangle):class PictureInPictureFrame(Rectangle):- CONFIG = {- "height": 3,- "aspect_ratio": 16.0 / 9.0- }+ CONFIG = {"height": 3, "aspect_ratio": 16.0 / 9.0}def __init__(self, **kwargs):digest_config(self, kwargs)Rectangle.__init__(- self,- width=self.aspect_ratio * self.height,- height=self.height,- **kwargs+ self, width=self.aspect_ratio * self.height, height=self.height, **kwargs)diff --git a/manim/mobject/functions.py b/manim/mobject/functions.pyindex d6a5fd04c..f12ec3767 100644--- a/manim/mobject/functions.py+++ b/manim/mobject/functions.py@@ -51,13 +51,11 @@ class ParametricFunction(VMobject):t_min, t_max = self.t_min, self.t_maxdt = self.dt- discontinuities = filter(- lambda t: t_min <= t <= t_max,- self.discontinuities- )+ discontinuities = filter(lambda t: t_min <= t <= t_max, self.discontinuities)discontinuities = np.array(list(discontinuities))boundary_times = [- self.t_min, self.t_max,+ self.t_min,+ self.t_max,*(discontinuities - dt),*(discontinuities + dt),]@@ -67,9 +65,7 @@ class ParametricFunction(VMobject):if t_range[-1] != t2:t_range.append(t2)points = np.array([self.function(t) for t in t_range])- valid_indices = np.apply_along_axis(- np.all, 1, np.isfinite(points)- )+ valid_indices = np.apply_along_axis(np.all, 1, np.isfinite(points))points = points[valid_indices]if len(points) > 0:self.start_new_path(points[0])@@ -81,20 +77,15 @@ class ParametricFunction(VMobject):class FunctionGraph(ParametricFunction):CONFIG = {"color": YELLOW,- "x_min": -config['frame_x_radius'],- "x_max": config['frame_x_radius'],+ "x_min": -config["frame_x_radius"],+ "x_max": config["frame_x_radius"],}def __init__(self, function, **kwargs):digest_config(self, kwargs)- self.parametric_function = \- lambda t: np.array([t, function(t), 0])+ self.parametric_function = lambda t: np.array([t, function(t), 0])ParametricFunction.__init__(- self,- self.parametric_function,- t_min=self.x_min,- t_max=self.x_max,- **kwargs+ self, self.parametric_function, t_min=self.x_min, t_max=self.x_max, **kwargs)self.function = functiondiff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.pyindex d9de953ac..9c0008562 100644--- a/manim/mobject/geometry.py+++ b/manim/mobject/geometry.py@@ -45,16 +45,14 @@ class TipableVMobject(VMobject):to the TipableVMobject instance's tip(s), its length etc"""+CONFIG = {"tip_length": DEFAULT_ARROW_TIP_LENGTH,# TODO"normal_vector": OUT,- "tip_style": {- "fill_opacity": 1,- "stroke_width": 0,- }+ "tip_style": {"fill_opacity": 1, "stroke_width": 0,},}-+# Adding, Creating, Modifying tipsdef add_tip(self, tip_length=None, at_start=False):@@ -86,10 +84,7 @@ class TipableVMobject(VMobject):if tip_length is None:tip_length = self.get_default_tip_length()color = self.get_color()- style = {- "fill_color": color,- "stroke_color": color- }+ style = {"fill_color": color, "stroke_color": color}style.update(self.tip_style)tip = ArrowTip(length=tip_length, **style)return tip@@ -103,10 +98,7 @@ class TipableVMobject(VMobject):else:handle = self.get_last_handle()anchor = self.get_end()- tip.rotate(- angle_of_vector(handle - anchor) -- PI - tip.get_angle()- )+ tip.rotate(angle_of_vector(handle - anchor) - PI - tip.get_angle())tip.shift(anchor - tip.get_tip_point())return tip@@ -117,9 +109,7 @@ class TipableVMobject(VMobject):return selfif at_start:- self.put_start_and_end_on(- tip.get_base(), self.get_end()- )+ self.put_start_and_end_on(tip.get_base(), self.get_end())else:self.put_start_and_end_on(self.get_start(), tip.get_base(),@@ -141,7 +131,6 @@ class TipableVMobject(VMobject):def has_start_tip(self):return hasattr(self, "start_tip") and self.start_tip in self-# Gettersdef pop_tips(self):@@ -214,7 +203,7 @@ class Arc(TipableVMobject):def __init__(self, start_angle=0, angle=TAU / 4, **kwargs):self.start_angle = start_angleself.angle = angle- self._failed_to_get_center=False+ self._failed_to_get_center = FalseVMobject.__init__(self, **kwargs)def generate_points(self):@@ -223,14 +212,16 @@ class Arc(TipableVMobject):self.shift(self.arc_center)def set_pre_positioned_points(self):- anchors = np.array([- np.cos(a) * RIGHT + np.sin(a) * UP- for a in np.linspace(- self.start_angle,- self.start_angle + self.angle,- self.num_components,- )- ])+ anchors = np.array(+ [+ np.cos(a) * RIGHT + np.sin(a) * UP+ for a in np.linspace(+ self.start_angle,+ self.start_angle + self.angle,+ self.num_components,+ )+ ]+ )# Figure out which control points will give the# Appropriate tangent lines to the circled_theta = self.angle / (self.num_components - 1.0)@@ -242,12 +233,10 @@ class Arc(TipableVMobject):handles1 = anchors[:-1] + (d_theta / 3) * tangent_vectors[:-1]handles2 = anchors[1:] - (d_theta / 3) * tangent_vectors[1:]self.set_anchors_and_handles(- anchors[:-1],- handles1, handles2,- anchors[1:],+ anchors[:-1], handles1, handles2, anchors[1:],)- def get_arc_center(self,warning=True):+ def get_arc_center(self, warning=True):"""Looks at the normals to the first twoanchors, and finds their intersection points@@ -261,14 +250,11 @@ class Arc(TipableVMobject):n1 = rotate_vector(t1, TAU / 4)n2 = rotate_vector(t2, TAU / 4)try:- return line_intersection(- line1=(a1, a1 + n1),- line2=(a2, a2 + n2),- )+ return line_intersection(line1=(a1, a1 + n1), line2=(a2, a2 + n2),)except Exception:if warning:warnings.warn("Can't find Arc center, using ORIGIN instead")- self._failed_to_get_center=True+ self._failed_to_get_center = Truereturn np.array(ORIGIN)def move_arc_center_to(self, point):@@ -276,45 +262,44 @@ class Arc(TipableVMobject):return selfdef stop_angle(self):- return angle_of_vector(- self.points[-1] - self.get_arc_center()- ) % TAU+ return angle_of_vector(self.points[-1] - self.get_arc_center()) % TAUclass ArcBetweenPoints(Arc):"""Inherits from Arc and additionally takes 2 points between which the arc is spanned."""+def __init__(self, start, end, angle=TAU / 4, radius=None, **kwargs):if radius is not None:- self.radius=radius+ self.radius = radiusif radius < 0:- sign=-2- radius*=(-1)+ sign = -2+ radius *= -1else:- sign=2- halfdist=np.linalg.norm(np.array(start) - np.array(end)) / 2+ sign = 2+ halfdist = np.linalg.norm(np.array(start) - np.array(end)) / 2if radius < halfdist:- raise ValueError("""ArcBetweenPoints called with a radius that is- smaller than half the distance between the points.""")- arc_height=radius - math.sqrt(radius ** 2 - halfdist ** 2)- angle=math.acos((radius - arc_height) / radius)*sign+ raise ValueError(+ """ArcBetweenPoints called with a radius that is+ smaller than half the distance between the points."""+ )+ arc_height = radius - math.sqrt(radius ** 2 - halfdist ** 2)+ angle = math.acos((radius - arc_height) / radius) * signArc.__init__(- self,- angle=angle,- **kwargs,+ self, angle=angle, **kwargs,)if angle == 0:self.set_points_as_corners([LEFT, RIGHT])self.put_start_and_end_on(start, end)-+if radius is None:- center=self.get_arc_center(warning=False)+ center = self.get_arc_center(warning=False)if not self._failed_to_get_center:- self.radius=np.linalg.norm(np.array(start) - np.array(center))+ self.radius = np.linalg.norm(np.array(start) - np.array(center))else:- self.radius=math.inf+ self.radius = math.infclass CurvedArrow(ArcBetweenPoints):@@ -325,18 +310,12 @@ class CurvedArrow(ArcBetweenPoints):class CurvedDoubleArrow(CurvedArrow):def __init__(self, start_point, end_point, **kwargs):- CurvedArrow.__init__(- self, start_point, end_point, **kwargs- )+ CurvedArrow.__init__(self, start_point, end_point, **kwargs)self.add_tip(at_start=True)class Circle(Arc):- CONFIG = {- "color": RED,- "close_new_points": True,- "anchors_span_full_range": False- }+ CONFIG = {"color": RED, "close_new_points": True, "anchors_span_full_range": False}def __init__(self, **kwargs):Arc.__init__(self, 0, TAU, **kwargs)@@ -349,18 +328,12 @@ class Circle(Arc):# TODO: Figure out and fixself.replace(mobject, dim_to_match, stretch)- self.set_width(- np.sqrt(mobject.get_width()**2 + mobject.get_height()**2)- )+ self.set_width(np.sqrt(mobject.get_width() ** 2 + mobject.get_height() ** 2))self.scale(buffer_factor)def point_at_angle(self, angle):- start_angle = angle_of_vector(- self.points[0] - self.get_center()- )- return self.point_from_proportion(- (angle - start_angle) / TAU- )+ start_angle = angle_of_vector(self.points[0] - self.get_center())+ return self.point_from_proportion((angle - start_angle) / TAU)class Dot(Circle):@@ -368,7 +341,7 @@ class Dot(Circle):"radius": DEFAULT_DOT_RADIUS,"stroke_width": 0,"fill_opacity": 1.0,- "color": WHITE+ "color": WHITE,}def __init__(self, point=ORIGIN, **kwargs):@@ -382,10 +355,7 @@ class SmallDot(Dot):class Ellipse(Circle):- CONFIG = {- "width": 2,- "height": 1- }+ CONFIG = {"width": 2, "height": 1}def __init__(self, **kwargs):Circle.__init__(self, **kwargs)@@ -422,10 +392,7 @@ class AnnularSector(Arc):class Sector(AnnularSector):- CONFIG = {- "outer_radius": 1,- "inner_radius": 0- }+ CONFIG = {"outer_radius": 1, "inner_radius": 0}class Annulus(Circle):@@ -461,10 +428,7 @@ class Line(TipableVMobject):def generate_points(self):if self.path_arc:- arc = ArcBetweenPoints(- self.start, self.end,- angle=self.path_arc- )+ arc = ArcBetweenPoints(self.start, self.end, angle=self.path_arc)self.set_points(arc.points)else:self.set_points_as_corners([self.start, self.end])@@ -486,9 +450,7 @@ class Line(TipableVMobject):if length < 2 * self.buff:returnbuff_proportion = self.buff / length- self.pointwise_become_partial(- self, buff_proportion, 1 - buff_proportion- )+ self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion)return selfdef set_start_and_end_attrs(self, start, end):@@ -536,8 +498,7 @@ class Line(TipableVMobject):def set_angle(self, angle):self.rotate(- angle - self.get_angle(),- about_point=self.get_start(),+ angle - self.get_angle(), about_point=self.get_start(),)def set_length(self, length):@@ -565,9 +526,7 @@ class DashedLine(Line):ps_ratio = self.positive_space_rationum_dashes = self.calculate_num_dashes(ps_ratio)dashes = DashedVMobject(- self,- num_dashes=num_dashes,- positive_space_ratio=ps_ratio+ self, num_dashes=num_dashes, positive_space_ratio=ps_ratio)self.clear_points()self.add(*dashes)@@ -575,17 +534,12 @@ class DashedLine(Line):def calculate_num_dashes(self, positive_space_ratio):try:full_length = self.dash_length / positive_space_ratio- return int(np.ceil(- self.get_length() / full_length- ))+ return int(np.ceil(self.get_length() / full_length))except ZeroDivisionError:return 1def calculate_positive_space_ratio(self):- return fdiv(- self.dash_length,- self.dash_length + self.dash_spacing,- )+ return fdiv(self.dash_length, self.dash_length + self.dash_spacing,)def get_start(self):if len(self.submobjects) > 0:@@ -607,10 +561,7 @@ class DashedLine(Line):class TangentLine(Line):- CONFIG = {- "length": 1,- "d_alpha": 1e-6- }+ CONFIG = {"length": 1, "d_alpha": 1e-6}def __init__(self, vmob, alpha, **kwargs):digest_config(self, kwargs)@@ -618,9 +569,7 @@ class TangentLine(Line):a1 = np.clip(alpha - da, 0, 1)a2 = np.clip(alpha + da, 0, 1)super().__init__(- vmob.point_from_proportion(a1),- vmob.point_from_proportion(a2),- **kwargs+ vmob.point_from_proportion(a1), vmob.point_from_proportion(a2), **kwargs)self.scale(self.length / self.get_length())@@ -692,18 +641,12 @@ class Arrow(Line):def get_default_tip_length(self):max_ratio = self.max_tip_length_to_length_ratio- return min(- self.tip_length,- max_ratio * self.get_length(),- )+ return min(self.tip_length, max_ratio * self.get_length(),)def set_stroke_width_from_length(self):max_ratio = self.max_stroke_width_to_length_ratioself.set_stroke(- width=min(- self.initial_stroke_width,- max_ratio * self.get_length(),- ),+ width=min(self.initial_stroke_width, max_ratio * self.get_length(),),family=False,)return self@@ -743,9 +686,7 @@ class Polygon(VMobject):def __init__(self, *vertices, **kwargs):VMobject.__init__(self, **kwargs)- self.set_points_as_corners(- [*vertices, vertices[0]]- )+ self.set_points_as_corners([*vertices, vertices[0]])def get_vertices(self):return self.get_start_anchors()@@ -768,7 +709,7 @@ class Polygon(VMobject):arc = ArcBetweenPoints(v2 - unit_vect1 * cut_off_length,v2 + unit_vect2 * cut_off_length,- angle=sign * angle+ angle=sign * angle,)arcs.append(arc)@@ -780,9 +721,7 @@ class Polygon(VMobject):line = Line(arc1.get_end(), arc2.get_start())# Make sure anchors are evenly distributedlen_ratio = line.get_length() / arc1.get_arc_length()- line.insert_n_curves(- int(arc1.get_num_curves() * len_ratio)- )+ line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))self.append_points(line.get_points())return self@@ -861,10 +800,7 @@ class Square(Rectangle):def __init__(self, **kwargs):digest_config(self, kwargs)Rectangle.__init__(- self,- height=self.side_length,- width=self.side_length,- **kwargs+ self, height=self.side_length, width=self.side_length, **kwargs)diff --git a/manim/mobject/matrix.py b/manim/mobject/matrix.pyindex f243134b1..4d132e46e 100644--- a/manim/mobject/matrix.py+++ b/manim/mobject/matrix.py@@ -19,10 +19,7 @@ def matrix_to_tex_string(matrix):n_rows, n_cols = matrix.shapeprefix = "\\left[ \\begin{array}{%s}" % ("c" * n_cols)suffix = "\\end{array} \\right]"- rows = [- " & ".join(row)- for row in matrix- ]+ rows = [" & ".join(row) for row in matrix]return prefix + " \\\\ ".join(rows) + suffix@@ -30,8 +27,7 @@ def matrix_to_mobject(matrix):return TexMobject(matrix_to_tex_string(matrix))-def vector_coordinate_label(vector_mob, integer_labels=True,- n_dim=2, color=WHITE):+def vector_coordinate_label(vector_mob, integer_labels=True, n_dim=2, color=WHITE):vect = np.array(vector_mob.get_end())if integer_labels:vect = np.round(vect).astype(int)@@ -78,7 +74,7 @@ class Matrix(VMobject):self.organize_mob_matrix(mob_matrix)self.elements = VGroup(*mob_matrix.flatten())self.add(self.elements)- self.add_brackets(self.left_bracket,self.right_bracket)+ self.add_brackets(self.left_bracket, self.right_bracket)self.center()self.mob_matrix = mob_matrixif self.add_background_rectangles_to_entries:@@ -98,16 +94,14 @@ class Matrix(VMobject):mob = matrix[i][j]mob.move_to(i * self.v_buff * DOWN + j * self.h_buff * RIGHT,- self.element_alignment_corner+ self.element_alignment_corner,)return self- def add_brackets(self, left = "\\big[", right = "\\big]"):+ def add_brackets(self, left="\\big[", right="\\big]"):bracket_pair = TexMobject(left, right)bracket_pair.scale(2)- bracket_pair.stretch_to_fit_height(- self.get_height() + 2 * self.bracket_v_buff- )+ bracket_pair.stretch_to_fit_height(self.get_height() + 2 * self.bracket_v_buff)l_bracket, r_bracket = bracket_pair.split()l_bracket.next_to(self, LEFT, self.bracket_h_buff)r_bracket.next_to(self, RIGHT, self.bracket_h_buff)@@ -116,10 +110,9 @@ class Matrix(VMobject):return selfdef get_columns(self):- return VGroup(*[- VGroup(*self.mob_matrix[:, i])- for i in range(self.mob_matrix.shape[1])- ])+ return VGroup(+ *[VGroup(*self.mob_matrix[:, i]) for i in range(self.mob_matrix.shape[1])]+ )def set_column_colors(self, *colors):columns = self.get_columns()@@ -135,10 +128,9 @@ class Matrix(VMobject):List[:class:`~.VGroup`]Each VGroup contains a row of the matrix."""- return VGroup(*[- VGroup(*self.mob_matrix[i, :])- for i in range(self.mob_matrix.shape[1])- ])+ return VGroup(+ *[VGroup(*self.mob_matrix[i, :]) for i in range(self.mob_matrix.shape[1])]+ )def set_row_colors(self, *colors):"""Set individual colors for each row of the matrix@@ -176,7 +168,7 @@ class Matrix(VMobject):class DecimalMatrix(Matrix):CONFIG = {"element_to_mobject": DecimalNumber,- "element_to_mobject_config": {"num_decimal_places": 1}+ "element_to_mobject_config": {"num_decimal_places": 1},}@@ -192,7 +184,9 @@ class MobjectMatrix(Matrix):}-def get_det_text(matrix, determinant=None, background_rect=False, initial_scale_factor=2):+def get_det_text(+ matrix, determinant=None, background_rect=False, initial_scale_factor=2+):parens = TexMobject("(", ")")parens.scale(initial_scale_factor)parens.stretch_to_fit_height(matrix.get_height())@@ -211,4 +205,4 @@ def get_det_text(matrix, determinant=None, background_rect=False, initial_scale_result = TexMobject(str(determinant))result.next_to(eq, RIGHT, buff=0.2)det_text.add(eq, result)- return det_text\ No newline at end of file+ return det_textdiff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.pyindex bb5866af5..d7947ab4d 100644--- a/manim/mobject/mobject.py+++ b/manim/mobject/mobject.py@@ -25,10 +25,12 @@ from ..utils.space_ops import rotation_matrix# TODO: Explain array_attrs+class Mobject(Container):"""Mathematical Object"""+CONFIG = {"color": WHITE,"name": None,@@ -88,7 +90,9 @@ class Mobject(Container):Ensures all attributes which are mobjects are includedin the submobjects list."""- mobject_attrs = [x for x in list(self.__dict__.values()) if isinstance(x, Mobject)]+ mobject_attrs = [+ x for x in list(self.__dict__.values()) if isinstance(x, Mobject)+ ]self.submobjects = list_update(self.submobjects, mobject_attrs)return self@@ -102,6 +106,7 @@ class Mobject(Container):def get_image(self, camera=None):if camera is None:from ..camera.camera import Camera+camera = Camera()camera.capture_mobject(self)return camera.get_image()@@ -111,7 +116,7 @@ class Mobject(Container):def save_image(self, name=None):self.get_image().save(- os.path.join(config['VIDEO_DIR'], (name or str(self)) + ".png")+ os.path.join(config["VIDEO_DIR"], (name or str(self)) + ".png"))def copy(self):@@ -121,9 +126,7 @@ class Mobject(Container):copy_mobject = copy.copy(self)copy_mobject.points = np.array(self.points)- copy_mobject.submobjects = [- submob.copy() for submob in self.submobjects- ]+ copy_mobject.submobjects = [submob.copy() for submob in self.submobjects]copy_mobject.updaters = list(self.updaters)family = self.get_family()for attr, value in list(self.__dict__.items()):@@ -161,10 +164,7 @@ class Mobject(Container):return selfdef get_time_based_updaters(self):- return [- updater for updater in self.updaters- if "dt" in get_parameters(updater)- ]+ return [updater for updater in self.updaters if "dt" in get_parameters(updater)]def has_time_based_updater(self):for updater in self.updaters:@@ -176,10 +176,7 @@ class Mobject(Container):return self.updatersdef get_family_updaters(self):- return list(it.chain(*[- sm.get_updaters()- for sm in self.get_family()- ]))+ return list(it.chain(*[sm.get_updaters() for sm in self.get_family()]))def add_updater(self, update_function, index=None, call_updater=True):if index is None:@@ -232,7 +229,7 @@ class Mobject(Container):def shift(self, *vectors):total_vector = reduce(op.add, vectors)for mob in self.family_members_with_points():- mob.points = mob.points.astype('float')+ mob.points = mob.points.astype("float")mob.points += total_vectorreturn self@@ -257,8 +254,7 @@ class Mobject(Container):def rotate(self, angle, axis=OUT, **kwargs):rot_matrix = rotation_matrix(angle, axis)self.apply_points_function_about_point(- lambda points: np.dot(points, rot_matrix.T),- **kwargs+ lambda points: np.dot(points, rot_matrix.T), **kwargs)return self@@ -269,6 +265,7 @@ class Mobject(Container):def func(points):points[:, dim] *= factorreturn points+self.apply_points_function_about_point(func, **kwargs)return self@@ -277,8 +274,7 @@ class Mobject(Container):if len(kwargs) == 0:kwargs["about_point"] = ORIGINself.apply_points_function_about_point(- lambda points: np.apply_along_axis(function, 1, points),- **kwargs+ lambda points: np.apply_along_axis(function, 1, points), **kwargs)return self@@ -297,10 +293,9 @@ class Mobject(Container):kwargs["about_point"] = ORIGINfull_matrix = np.identity(self.dim)matrix = np.array(matrix)- full_matrix[:matrix.shape[0], :matrix.shape[1]] = matrix+ full_matrix[: matrix.shape[0], : matrix.shape[1]] = matrixself.apply_points_function_about_point(- lambda points: np.dot(points, full_matrix.T),- **kwargs+ lambda points: np.dot(points, full_matrix.T), **kwargs)return self@@ -308,11 +303,8 @@ class Mobject(Container):def R3_func(point):x, y, z = pointxy_complex = function(complex(x, y))- return [- xy_complex.real,- xy_complex.imag,- z- ]+ return [xy_complex.real, xy_complex.imag, z]+return self.apply_function(R3_func)def wag(self, direction=RIGHT, axis=DOWN, wag_factor=1.0):@@ -320,29 +312,26 @@ class Mobject(Container):alphas = np.dot(mob.points, np.transpose(axis))alphas -= min(alphas)alphas /= max(alphas)- alphas = alphas**wag_factor+ alphas = alphas ** wag_factormob.points += np.dot(alphas.reshape((len(alphas), 1)),- np.array(direction).reshape((1, mob.dim))+ np.array(direction).reshape((1, mob.dim)),)return selfdef reverse_points(self):for mob in self.family_members_with_points():- mob.apply_over_attr_arrays(- lambda arr: np.array(list(reversed(arr)))- )+ mob.apply_over_attr_arrays(lambda arr: np.array(list(reversed(arr))))return selfdef repeat(self, count):"""This can make transition animations nicer"""+def repeat_array(array):- return reduce(- lambda a1, a2: np.append(a1, a2, axis=0),- [array] * count- )+ return reduce(lambda a1, a2: np.append(a1, a2, axis=0), [array] * count)+for mob in self.family_members_with_points():mob.apply_over_attr_arrays(repeat_array)return self@@ -351,7 +340,9 @@ class Mobject(Container):# Note, much of these are now redundant with default behavior of# above methods- def apply_points_function_about_point(self, func, about_point=None, about_edge=None):+ def apply_points_function_about_point(+ self, func, about_point=None, about_edge=None+ ):if about_point is None:if about_edge is None:about_edge = ORIGIN@@ -389,7 +380,11 @@ class Mobject(Container):Direction just needs to be a vector pointing towards side orcorner in the 2d plane."""- target_point = np.sign(direction) * (config['frame_x_radius'], config['frame_y_radius'], 0)+ target_point = np.sign(direction) * (+ config["frame_x_radius"],+ config["frame_y_radius"],+ 0,+ )point_to_align = self.get_critical_point(direction)shift_val = target_point - point_to_align - buff * np.array(direction)shift_val = shift_val * abs(np.sign(direction))@@ -402,23 +397,23 @@ class Mobject(Container):def to_edge(self, edge=LEFT, buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER):return self.align_on_border(edge, buff)- def next_to(self, mobject_or_point,- direction=RIGHT,- buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,- aligned_edge=ORIGIN,- submobject_to_align=None,- index_of_submobject_to_align=None,- coor_mask=np.array([1, 1, 1]),- ):+ def next_to(+ self,+ mobject_or_point,+ direction=RIGHT,+ buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,+ aligned_edge=ORIGIN,+ submobject_to_align=None,+ index_of_submobject_to_align=None,+ coor_mask=np.array([1, 1, 1]),+ ):if isinstance(mobject_or_point, Mobject):mob = mobject_or_pointif index_of_submobject_to_align is not None:target_aligner = mob[index_of_submobject_to_align]else:target_aligner = mob- target_point = target_aligner.get_critical_point(- aligned_edge + direction- )+ target_point = target_aligner.get_critical_point(aligned_edge + direction)else:target_point = mobject_or_pointif submobject_to_align is not None:@@ -428,12 +423,11 @@ class Mobject(Container):else:aligner = selfpoint_to_align = aligner.get_critical_point(aligned_edge - direction)- self.shift((target_point - point_to_align +- buff * direction) * coor_mask)+ self.shift((target_point - point_to_align + buff * direction) * coor_mask)return selfdef shift_onto_screen(self, **kwargs):- space_lengths = [config['frame_x_radius'], config['frame_y_radius']]+ space_lengths = [config["frame_x_radius"], config["frame_y_radius"]]for vect in UP, DOWN, LEFT, RIGHT:dim = np.argmax(np.abs(vect))buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_EDGE_BUFFER)@@ -444,13 +438,13 @@ class Mobject(Container):return selfdef is_off_screen(self):- if self.get_left()[0] > config['frame_x_radius']:+ if self.get_left()[0] > config["frame_x_radius"]:return True- if self.get_right()[0] < -config['frame_x_radius']:+ if self.get_right()[0] < -config["frame_x_radius"]:return True- if self.get_bottom()[1] > config['frame_y_radius']:+ if self.get_bottom()[1] > config["frame_y_radius"]:return True- if self.get_top()[1] < -config['frame_y_radius']:+ if self.get_top()[1] < -config["frame_y_radius"]:return Truereturn False@@ -508,11 +502,12 @@ class Mobject(Container):def space_out_submobjects(self, factor=1.5, **kwargs):self.scale(factor, **kwargs)for submob in self.submobjects:- submob.scale(1. / factor)+ submob.scale(1.0 / factor)return self- def move_to(self, point_or_mobject, aligned_edge=ORIGIN,- coor_mask=np.array([1, 1, 1])):+ def move_to(+ self, point_or_mobject, aligned_edge=ORIGIN, coor_mask=np.array([1, 1, 1])+ ):if isinstance(point_or_mobject, Mobject):target = point_or_mobject.get_critical_point(aligned_edge)else:@@ -530,17 +525,12 @@ class Mobject(Container):self.stretch_to_fit_height(mobject.get_height())else:self.rescale_to_fit(- mobject.length_over_dim(dim_to_match),- dim_to_match,- stretch=False+ mobject.length_over_dim(dim_to_match), dim_to_match, stretch=False)self.shift(mobject.get_center() - self.get_center())return self- def surround(self, mobject,- dim_to_match=0,- stretch=False,- buff=MED_SMALL_BUFF):+ def surround(self, mobject, dim_to_match=0, stretch=False, buff=MED_SMALL_BUFF):self.replace(mobject, dim_to_match, stretch)length = mobject.length_over_dim(dim_to_match)self.scale_in_place((length + buff) / length)@@ -553,13 +543,11 @@ class Mobject(Container):raise Exception("Cannot position endpoints of closed loop")target_vect = np.array(end) - np.array(start)self.scale(- get_norm(target_vect) / get_norm(curr_vect),- about_point=curr_start,+ get_norm(target_vect) / get_norm(curr_vect), about_point=curr_start,)self.rotate(- angle_of_vector(target_vect) -- angle_of_vector(curr_vect),- about_point=curr_start+ angle_of_vector(target_vect) - angle_of_vector(curr_vect),+ about_point=curr_start,)self.shift(start - curr_start)return self@@ -569,10 +557,9 @@ class Mobject(Container):# TODO, this does not behave well when the mobject has points,# since it gets displayed on topfrom ..mobject.shape_matchers import BackgroundRectangle+self.background_rectangle = BackgroundRectangle(- self, color=color,- fill_opacity=opacity,- **kwargs+ self, color=color, fill_opacity=opacity, **kwargs)self.add_to_back(self.background_rectangle)return self@@ -606,9 +593,12 @@ class Mobject(Container):self.set_submobject_colors_by_gradient(*colors)return self- def set_colors_by_radial_gradient(self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK):+ def set_colors_by_radial_gradient(+ self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK+ ):self.set_submobject_colors_by_radial_gradient(- center, radius, inner_color, outer_color)+ center, radius, inner_color, outer_color+ )return selfdef set_submobject_colors_by_gradient(self, *colors):@@ -624,7 +614,9 @@ class Mobject(Container):mob.set_color(color, family=False)return self- def set_submobject_colors_by_radial_gradient(self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK):+ def set_submobject_colors_by_radial_gradient(+ self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK+ ):if center is None:center = self.get_center()@@ -642,9 +634,7 @@ class Mobject(Container):def fade_to(self, color, alpha, family=True):if self.get_num_points() > 0:- new_color = interpolate_color(- self.get_color(), color, alpha- )+ new_color = interpolate_color(self.get_color(), color, alpha)self.set_color(new_color, family=False)if family:for submob in self.submobjects:@@ -691,17 +681,15 @@ class Mobject(Container):def nonempty_submobjects(self):return [- submob for submob in self.submobjects+ submob+ for submob in self.submobjectsif len(submob.submobjects) != 0 or len(submob.points) != 0]def get_merged_array(self, array_attr):result = getattr(self, array_attr)for submob in self.submobjects:- result = np.append(- result, submob.get_merged_array(array_attr),- axis=0- )+ result = np.append(result, submob.get_merged_array(array_attr), axis=0)submob.get_merged_array(array_attr)return result@@ -781,10 +769,9 @@ class Mobject(Container):return self.get_edge_center(IN)def length_over_dim(self, dim):- return (- self.reduce_across_dimension(np.max, np.max, dim) -- self.reduce_across_dimension(np.min, np.min, dim)- )+ return self.reduce_across_dimension(+ np.max, np.max, dim+ ) - self.reduce_across_dimension(np.min, np.min, dim)def get_width(self):return self.length_over_dim(0)@@ -799,9 +786,7 @@ class Mobject(Container):"""Meant to generalize get_x, get_y, get_z"""- return self.get_extremum_along_dim(- dim=dim, key=direction[dim]- )+ return self.get_extremum_along_dim(dim=dim, key=direction[dim])def get_x(self, direction=ORIGIN):return self.get_coord(0, direction)@@ -824,18 +809,18 @@ class Mobject(Container):return self.get_start(), self.get_end()def point_from_proportion(self, alpha):- raise NotImplementedError('Please override in a child class.')+ raise NotImplementedError("Please override in a child class.")def get_pieces(self, n_pieces):template = self.copy()template.submobjects = []alphas = np.linspace(0, 1, n_pieces + 1)- return Group(*[- template.copy().pointwise_become_partial(- self, a1, a2- )- for a1, a2 in zip(alphas[:-1], alphas[1:])- ])+ return Group(+ *[+ template.copy().pointwise_become_partial(self, a1, a2)+ for a1, a2 in zip(alphas[:-1], alphas[1:])+ ]+ )def get_z_index_reference_point(self):# TODO, better place to define default z_index_group?@@ -854,10 +839,7 @@ class Mobject(Container):return self.set_color(mobject.get_color())def match_dim_size(self, mobject, dim, **kwargs):- return self.rescale_to_fit(- mobject.length_over_dim(dim), dim,- **kwargs- )+ return self.rescale_to_fit(mobject.length_over_dim(dim), dim, **kwargs)def match_width(self, mobject, **kwargs):return self.match_dim_size(mobject, 0, **kwargs)@@ -870,9 +852,7 @@ class Mobject(Container):def match_coord(self, mobject, dim, direction=ORIGIN):return self.set_coord(- mobject.get_coord(dim, direction),- dim=dim,- direction=direction,+ mobject.get_coord(dim, direction), dim=dim, direction=direction,)def match_x(self, mobject, direction=ORIGIN):@@ -954,10 +934,12 @@ class Mobject(Container):v1 = DOWNv2 = RIGHTn = len(submobs) // n_cols- Group(*[- Group(*submobs[i:i + n]).arrange(v1, **kwargs)- for i in range(0, len(submobs), n)- ]).arrange(v2, **kwargs)+ Group(+ *[+ Group(*submobs[i : i + n]).arrange(v1, **kwargs)+ for i in range(0, len(submobs), n)+ ]+ ).arrange(v2, **kwargs)return selfdef sort(self, point_to_num_func=lambda p: p[0], submob_func=None):@@ -1009,7 +991,7 @@ class Mobject(Container):return selfdef align_points_with_larger(self, larger_mobject):- raise NotImplementedError('Please override in a child class.')+ raise NotImplementedError("Please override in a child class.")def align_submobjects(self, mobject):mob1 = self@@ -1046,50 +1028,39 @@ class Mobject(Container):curr = len(self.submobjects)if curr == 0:# If empty, simply add n point mobjects- self.submobjects = [- self.get_point_mobject()- for k in range(n)- ]+ self.submobjects = [self.get_point_mobject() for k in range(n)]returntarget = curr + n# TODO, factor this out to utils so as to reuse# with VMobject.insert_n_curvesrepeat_indices = (np.arange(target) * curr) // target- split_factors = [- sum(repeat_indices == i)- for i in range(curr)- ]+ split_factors = [sum(repeat_indices == i) for i in range(curr)]new_submobs = []for submob, sf in zip(self.submobjects, split_factors):new_submobs.append(submob)for k in range(1, sf):- new_submobs.append(- submob.copy().fade(1)- )+ new_submobs.append(submob.copy().fade(1))self.submobjects = new_submobsreturn selfdef repeat_submobject(self, submob):return submob.copy()- def interpolate(self, mobject1, mobject2,- alpha, path_func=straight_path):+ def interpolate(self, mobject1, mobject2, alpha, path_func=straight_path):"""Turns self into an interpolation between mobject1and mobject2."""- self.points = path_func(- mobject1.points, mobject2.points, alpha- )+ self.points = path_func(mobject1.points, mobject2.points, alpha)self.interpolate_color(mobject1, mobject2, alpha)return selfdef interpolate_color(self, mobject1, mobject2, alpha):- raise NotImplementedError('Please override in a child class.')+ raise NotImplementedError("Please override in a child class.")def pointwise_become_partial(self, mobject, a, b):- raise NotImplementedError('Please override in a child class.')+ raise NotImplementedError("Please override in a child class.")def become(self, mobject, copy_submobjects=True):"""@@ -1105,8 +1076,7 @@ class Mobject(Container):# Errorsdef throw_error_if_no_points(self):if self.has_no_points():- message = "Cannot call Mobject.{} " +\- "for a Mobject with no points"+ message = "Cannot call Mobject.{} " + "for a Mobject with no points"caller_name = sys._getframe(1).f_code.co_nameraise Exception(message.format(caller_name))diff --git a/manim/mobject/mobject_update_utils.py b/manim/mobject/mobject_update_utils.pyindex 896b8f41e..ef40a8773 100644--- a/manim/mobject/mobject_update_utils.py+++ b/manim/mobject/mobject_update_utils.py@@ -7,9 +7,9 @@ from ..mobject.mobject import Mobjectdef assert_is_mobject_method(method):- assert(inspect.ismethod(method))+ assert inspect.ismethod(method)mobject = method.__self__- assert(isinstance(mobject, Mobject))+ assert isinstance(mobject, Mobject)def always(method, *args, **kwargs):@@ -31,10 +31,7 @@ def f_always(method, *arg_generators, **kwargs):func = method.__func__def updater(mob):- args = [- arg_generator()- for arg_generator in arg_generators- ]+ args = [arg_generator() for arg_generator in arg_generators]func(mob, *args, **kwargs)mobject.add_updater(updater)@@ -48,16 +45,12 @@ def always_redraw(func):def always_shift(mobject, direction=RIGHT, rate=0.1):- mobject.add_updater(- lambda m, dt: m.shift(dt * rate * direction)- )+ mobject.add_updater(lambda m, dt: m.shift(dt * rate * direction))return mobjectdef always_rotate(mobject, rate=20 * DEGREES, **kwargs):- mobject.add_updater(- lambda m, dt: m.rotate(dt * rate, **kwargs)- )+ mobject.add_updater(lambda m, dt: m.rotate(dt * rate, **kwargs))return mobject@@ -95,6 +88,4 @@ def turn_animation_into_updater(animation, cycle=False, **kwargs):def cycle_animation(animation, **kwargs):- return turn_animation_into_updater(- animation, cycle=True, **kwargs- )\ No newline at end of file+ return turn_animation_into_updater(animation, cycle=True, **kwargs)diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.pyindex 512465fc6..da8f286ee 100644--- a/manim/mobject/number_line.py+++ b/manim/mobject/number_line.py@@ -15,8 +15,8 @@ from ..utils.space_ops import normalizeclass NumberLine(Line):CONFIG = {"color": LIGHT_GREY,- "x_min": -config['frame_x_radius'],- "x_max": config['frame_x_radius'],+ "x_min": -config["frame_x_radius"],+ "x_max": config["frame_x_radius"],"unit_size": 1,"include_ticks": True,"tick_size": 0.1,@@ -37,10 +37,8 @@ class NumberLine(Line):"tip_width": 0.25,"tip_height": 0.25,"add_start": 0, # extend number line by this amount at its starting point- "add_end": 0, # extend number line by this amount at its end point- "decimal_number_config": {- "num_decimal_places": 0,- },+ "add_end": 0, # extend number line by this amount at its end point+ "decimal_number_config": {"num_decimal_places": 0,},"exclude_zero_from_default_numbers": False,}@@ -49,10 +47,7 @@ class NumberLine(Line):start = self.unit_size * self.x_min * RIGHTend = self.unit_size * self.x_max * RIGHTLine.__init__(- self,- start - self.add_start * RIGHT,- end + self.add_end * RIGHT,- **kwargs+ self, start - self.add_start * RIGHT, end + self.add_end * RIGHT, **kwargs)self.shift(-self.number_to_point(self.number_at_center))@@ -67,24 +62,23 @@ class NumberLine(Line):def init_leftmost_tick(self):if self.leftmost_tick is None:self.leftmost_tick = op.mul(- self.tick_frequency,- np.ceil(self.x_min / self.tick_frequency)+ self.tick_frequency, np.ceil(self.x_min / self.tick_frequency))def add_tick_marks(self):tick_size = self.tick_size- self.tick_marks = VGroup(*[- self.get_tick(x, tick_size)- for x in self.get_tick_numbers()- ])+ self.tick_marks = VGroup(+ *[self.get_tick(x, tick_size) for x in self.get_tick_numbers()]+ )big_tick_size = tick_size * self.longer_tick_multiple- self.big_tick_marks = VGroup(*[- self.get_tick(x, big_tick_size)- for x in self.numbers_with_elongated_ticks- ])+ self.big_tick_marks = VGroup(+ *[+ self.get_tick(x, big_tick_size)+ for x in self.numbers_with_elongated_ticks+ ]+ )self.add(- self.tick_marks,- self.big_tick_marks,+ self.tick_marks, self.big_tick_marks,)def get_tick(self, x, size=None):@@ -97,17 +91,14 @@ class NumberLine(Line):return resultdef get_tick_marks(self):- return VGroup(- *self.tick_marks,- *self.big_tick_marks,- )+ return VGroup(*self.tick_marks, *self.big_tick_marks,)def get_tick_numbers(self):u = -1 if self.include_tip and self.add_end == 0 else 1return np.arange(self.leftmost_tick,self.x_max + u * self.tick_frequency / 2,- self.tick_frequency+ self.tick_frequency,)def number_to_point(self, number):@@ -115,7 +106,7 @@ class NumberLine(Line):return interpolate(self.get_start() + self.add_start * RIGHT,self.get_end() - self.add_end * RIGHT,- alpha+ alpha,)def point_to_number(self, point):@@ -126,10 +117,7 @@ class NumberLine(Line):def distance_from_start(p):return np.dot(p - start_point, unit_vect)- proportion = fdiv(- distance_from_start(point),- distance_from_start(end_point)- )+ proportion = fdiv(distance_from_start(point), distance_from_start(end_point))return interpolate(self.x_min, self.x_max, proportion)def n2p(self, number):@@ -146,22 +134,16 @@ class NumberLine(Line):def default_numbers_to_display(self):if self.numbers_to_show is not None:return self.numbers_to_show- numbers = np.arange(- np.floor(self.leftmost_tick),- np.ceil(self.x_max),- )+ numbers = np.arange(np.floor(self.leftmost_tick), np.ceil(self.x_max),)if self.exclude_zero_from_default_numbers:numbers = numbers[numbers != 0]return numbers- def get_number_mobject(self, number,- number_config=None,- scale_val=None,- direction=None,- buff=None):+ def get_number_mobject(+ self, number, number_config=None, scale_val=None, direction=None, buff=None+ ):number_config = merge_dicts_recursively(- self.decimal_number_config,- number_config or {},+ self.decimal_number_config, number_config or {},)if scale_val is None:scale_val = self.number_scale_val@@ -171,28 +153,21 @@ class NumberLine(Line):num_mob = DecimalNumber(number, **number_config)num_mob.scale(scale_val)- num_mob.next_to(- self.number_to_point(number),- direction=direction,- buff=buff- )+ num_mob.next_to(self.number_to_point(number), direction=direction, buff=buff)return num_mobdef get_number_mobjects(self, *numbers, **kwargs):if len(numbers) == 0:numbers = self.default_numbers_to_display()- return VGroup(*[- self.get_number_mobject(number, **kwargs)- for number in numbers- ])+ return VGroup(+ *[self.get_number_mobject(number, **kwargs) for number in numbers]+ )def get_labels(self):return self.get_number_mobjects()def add_numbers(self, *numbers, **kwargs):- self.numbers = self.get_number_mobjects(- *numbers, **kwargs- )+ self.numbers = self.get_number_mobjects(*numbers, **kwargs)self.add(self.numbers)return self@@ -205,7 +180,5 @@ class UnitInterval(NumberLine):"tick_frequency": 0.1,"numbers_with_elongated_ticks": [0, 1],"number_at_center": 0.5,- "decimal_number_config": {- "num_decimal_places": 1,- }+ "decimal_number_config": {"num_decimal_places": 1,},}diff --git a/manim/mobject/numbers.py b/manim/mobject/numbers.pyindex 512b7d37a..6c5caf3ac 100644--- a/manim/mobject/numbers.py+++ b/manim/mobject/numbers.py@@ -33,10 +33,7 @@ class DecimalNumber(VMobject):else:num_string = num_string[1:]- self.add(*[- SingleStringTexMobject(char, **kwargs)- for char in num_string- ])+ self.add(*[SingleStringTexMobject(char, **kwargs) for char in num_string])# Add non-numerical bitsif self.show_ellipsis:@@ -44,26 +41,20 @@ class DecimalNumber(VMobject):if num_string.startswith("-"):minus = self.submobjects[0]- minus.next_to(- self.submobjects[1], LEFT,- buff=self.digit_to_digit_buff- )+ minus.next_to(self.submobjects[1], LEFT, buff=self.digit_to_digit_buff)if self.unit is not None:self.unit_sign = SingleStringTexMobject(self.unit, color=self.color)self.add(self.unit_sign)- self.arrange(- buff=self.digit_to_digit_buff,- aligned_edge=DOWN- )+ self.arrange(buff=self.digit_to_digit_buff, aligned_edge=DOWN)# Handle alignment of parts that should be aligned# to the bottomfor i, c in enumerate(num_string):if c == "-" and len(num_string) > i + 1:self[i].align_to(self[i + 1], UP)- self[i].shift(self[i+1].get_height() * DOWN / 2)+ self[i].shift(self[i + 1].get_height() * DOWN / 2)elif c == ",":self[i].shift(self[i].get_height() * DOWN / 2)if self.unit and self.unit.startswith("^"):@@ -82,31 +73,35 @@ class DecimalNumber(VMobject):- num_decimal_places- field_name (e.g. 0 or 0.real)"""- config = dict([- (attr, getattr(self, attr))- for attr in [- "include_sign",- "group_with_commas",- "num_decimal_places",+ config = dict(+ [+ (attr, getattr(self, attr))+ for attr in ["include_sign", "group_with_commas", "num_decimal_places",]]- ])+ )config.update(kwargs)- return "".join([- "{",- config.get("field_name", ""),- ":",- "+" if config["include_sign"] else "",- "," if config["group_with_commas"] else "",- ".", str(config["num_decimal_places"]), "f",- "}",- ])+ return "".join(+ [+ "{",+ config.get("field_name", ""),+ ":",+ "+" if config["include_sign"] else "",+ "," if config["group_with_commas"] else "",+ ".",+ str(config["num_decimal_places"]),+ "f",+ "}",+ ]+ )def get_complex_formatter(self, **kwargs):- return "".join([- self.get_formatter(field_name="0.real"),- self.get_formatter(field_name="0.imag", include_sign=True),- "i"- ])+ return "".join(+ [+ self.get_formatter(field_name="0.real"),+ self.get_formatter(field_name="0.imag", include_sign=True),+ "i",+ ]+ )def set_value(self, number, **config):full_config = dict(self.CONFIG)@@ -114,9 +109,7 @@ class DecimalNumber(VMobject):full_config.update(config)new_decimal = DecimalNumber(number, **full_config)# Make sure last digit has constant height- new_decimal.scale(- self[-1].get_height() / new_decimal[-1].get_height()- )+ new_decimal.scale(self[-1].get_height() / new_decimal[-1].get_height())new_decimal.move_to(self, self.edge_to_fix)new_decimal.match_style(self)@@ -142,4 +135,4 @@ class Integer(DecimalNumber):}def get_value(self):- return int(np.round(super().get_value()))\ No newline at end of file+ return int(np.round(super().get_value()))diff --git a/manim/mobject/probability.py b/manim/mobject/probability.pyindex db8de58a2..49d09083d 100644--- a/manim/mobject/probability.py+++ b/manim/mobject/probability.py@@ -59,18 +59,10 @@ class SampleSpace(Rectangle):parts.add(part)return parts- def get_horizontal_division(- self, p_list,- colors=[GREEN_E, BLUE_E],- vect=DOWN- ):+ def get_horizontal_division(self, p_list, colors=[GREEN_E, BLUE_E], vect=DOWN):return self.get_division_along_dimension(p_list, 1, colors, vect)- def get_vertical_division(- self, p_list,- colors=[MAROON_B, YELLOW],- vect=RIGHT- ):+ def get_vertical_division(self, p_list, colors=[MAROON_B, YELLOW], vect=RIGHT):return self.get_division_along_dimension(p_list, 0, colors, vect)def divide_horizontally(self, *args, **kwargs):@@ -82,18 +74,12 @@ class SampleSpace(Rectangle):self.add(self.vertical_parts)def get_subdivision_braces_and_labels(- self, parts, labels, direction,- buff=SMALL_BUFF,- min_num_quads=1+ self, parts, labels, direction, buff=SMALL_BUFF, min_num_quads=1):label_mobs = VGroup()braces = VGroup()for label, part in zip(labels, parts):- brace = Brace(- part, direction,- min_num_quads=min_num_quads,- buff=buff- )+ brace = Brace(part, direction, min_num_quads=min_num_quads, buff=buff)if isinstance(label, Mobject):label_mob = labelelse:@@ -113,17 +99,19 @@ class SampleSpace(Rectangle):return VGroup(parts.braces, parts.labels)def get_side_braces_and_labels(self, labels, direction=LEFT, **kwargs):- assert(hasattr(self, "horizontal_parts"))+ assert hasattr(self, "horizontal_parts")parts = self.horizontal_parts- return self.get_subdivision_braces_and_labels(parts, labels, direction, **kwargs)+ return self.get_subdivision_braces_and_labels(+ parts, labels, direction, **kwargs+ )def get_top_braces_and_labels(self, labels, **kwargs):- assert(hasattr(self, "vertical_parts"))+ assert hasattr(self, "vertical_parts")parts = self.vertical_partsreturn self.get_subdivision_braces_and_labels(parts, labels, UP, **kwargs)def get_bottom_braces_and_labels(self, labels, **kwargs):- assert(hasattr(self, "vertical_parts"))+ assert hasattr(self, "vertical_parts")parts = self.vertical_partsreturn self.get_subdivision_braces_and_labels(parts, labels, DOWN, **kwargs)@@ -223,10 +211,8 @@ class BarChart(VGroup):def change_bar_values(self, values):for bar, value in zip(self.bars, values):bar_bottom = bar.get_bottom()- bar.stretch_to_fit_height(- (value / self.max_value) * self.height- )+ bar.stretch_to_fit_height((value / self.max_value) * self.height)bar.move_to(bar_bottom, DOWN)def copy(self):- return self.deepcopy()\ No newline at end of file+ return self.deepcopy()diff --git a/manim/mobject/shape_matchers.py b/manim/mobject/shape_matchers.pyindex 2588eebd0..00b8c54a4 100644--- a/manim/mobject/shape_matchers.py+++ b/manim/mobject/shape_matchers.py@@ -27,7 +27,7 @@ class BackgroundRectangle(SurroundingRectangle):"stroke_width": 0,"stroke_opacity": 0,"fill_opacity": 0.75,- "buff": 0+ "buff": 0,}def __init__(self, mobject, **kwargs):@@ -38,20 +38,21 @@ class BackgroundRectangle(SurroundingRectangle):self.set_fill(opacity=b * self.original_fill_opacity)return self- def set_style_data(self,- stroke_color=None,- stroke_width=None,- fill_color=None,- fill_opacity=None,- family=True- ):+ def set_style_data(+ self,+ stroke_color=None,+ stroke_width=None,+ fill_color=None,+ fill_opacity=None,+ family=True,+ ):# Unchangable style, except for fill_opacityVMobject.set_style_data(self,stroke_color=BLACK,stroke_width=0,fill_color=BLACK,- fill_opacity=fill_opacity+ fill_opacity=fill_opacity,)return self@@ -66,10 +67,9 @@ class Cross(VGroup):}def __init__(self, mobject, **kwargs):- VGroup.__init__(self,- Line(UP + LEFT, DOWN + RIGHT),- Line(UP + RIGHT, DOWN + LEFT),- )+ VGroup.__init__(+ self, Line(UP + LEFT, DOWN + RIGHT), Line(UP + RIGHT, DOWN + LEFT),+ )self.replace(mobject, stretch=True)self.set_stroke(self.stroke_color, self.stroke_width)@@ -82,4 +82,4 @@ class Underline(Line):def __init__(self, mobject, **kwargs):super().__init__(LEFT, RIGHT, **kwargs)self.match_width(mobject)- self.next_to(mobject, DOWN, buff=self.buff)\ No newline at end of file+ self.next_to(mobject, DOWN, buff=self.buff)diff --git a/manim/mobject/svg/brace.py b/manim/mobject/svg/brace.pyindex 7f8b2888c..4effdf91c 100644--- a/manim/mobject/svg/brace.py+++ b/manim/mobject/svg/brace.py@@ -31,7 +31,8 @@ class Brace(TexMobject):# Adding int(target_width) qquads gives approximately the right widthnum_quads = np.clip(int(self.width_multiplier * target_width),- self.min_num_quads, self.max_num_quads+ self.min_num_quads,+ self.max_num_quads,)tex_string = "\\underbrace{%s}" % (num_quads * "\\qquad")TexMobject.__init__(self, tex_string, **kwargs)@@ -43,11 +44,7 @@ class Brace(TexMobject):def put_at_tip(self, mob, use_next_to=True, **kwargs):if use_next_to:- mob.next_to(- self.get_tip(),- np.round(self.get_direction()),- **kwargs- )+ mob.next_to(self.get_tip(), np.round(self.get_direction()), **kwargs)else:mob.move_to(self.get_tip())buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_MOBJECT_BUFFER)@@ -134,6 +131,4 @@ class BraceLabel(VMobject):class BraceText(BraceLabel):- CONFIG = {- "label_constructor": TextMobject- }\ No newline at end of file+ CONFIG = {"label_constructor": TextMobject}diff --git a/manim/mobject/svg/code_mobject.py b/manim/mobject/svg/code_mobject.pyindex a2a9ea469..2129562b3 100644--- a/manim/mobject/svg/code_mobject.py+++ b/manim/mobject/svg/code_mobject.py@@ -11,7 +11,7 @@ from pygments import highlightfrom pygments.lexers import get_lexer_by_namefrom pygments.formatters.html import HtmlFormatter-'''+"""1) Code is VGroup() with three things1.1) Code[0] is Code.background_mobjectwhich can be a@@ -27,7 +27,7 @@ from pygments.formatters.html import HtmlFormatterfirst character of line number 1Code.code[1][0:5] or Code.code[1][0:5]first five characters of line number 1-'''+"""class Code(VGroup):@@ -36,18 +36,18 @@ class Code(VGroup):"line_spacing": 0.1,"scale_factor": 0.5,"run_time": 1,- "font": 'Monospac821 BT',- 'stroke_width': 0,- 'margin': 0.3,- 'indentation_char': " ",+ "font": "Monospac821 BT",+ "stroke_width": 0,+ "margin": 0.3,+ "indentation_char": " ","background": "rectangle", # or window"corner_radius": 0.2,- 'insert_line_no': True,- 'line_no_from': 1,+ "insert_line_no": True,+ "line_no_from": 1,"line_no_buff": 0.4,- 'style': 'vim',- 'language': 'cpp',- 'generate_html_file': False+ "style": "vim",+ "language": "cpp",+ "generate_html_file": False,}def __init__(self, file_name=None, **kwargs):@@ -57,7 +57,7 @@ class Code(VGroup):self.style = self.style.lower()self.gen_html_string()strati = self.html_string.find("background:")- self.background_color = self.html_string[strati + 12:strati + 19]+ self.background_color = self.html_string[strati + 12 : strati + 19]self.gen_code_json()self.code = self.gen_colored_lines()@@ -70,11 +70,14 @@ class Code(VGroup):forground = VGroup(self.code, self.line_numbers)else:forground = self.code- self.background_mobject = SurroundingRectangle(forground, buff=self.margin,- color=self.background_color,- fill_color=self.background_color,- stroke_width=0,- fill_opacity=1, )+ self.background_mobject = SurroundingRectangle(+ forground,+ buff=self.margin,+ color=self.background_color,+ fill_color=self.background_color,+ stroke_width=0,+ fill_opacity=1,+ )self.background_mobject.round_corners(self.corner_radius)else:if self.insert_line_no:@@ -85,17 +88,24 @@ class Code(VGroup):height = forground.get_height() + 0.1 * 3 + 2 * self.marginwidth = forground.get_width() + 0.1 * 3 + 2 * self.margin- rrect = RoundedRectangle(corner_radius=self.corner_radius, height=height, width=width,- stroke_width=0,- color=self.background_color, fill_opacity=1)- red_button = Dot(radius=0.1, stroke_width=0, color='#ff5f56')+ rrect = RoundedRectangle(+ corner_radius=self.corner_radius,+ height=height,+ width=width,+ stroke_width=0,+ color=self.background_color,+ fill_opacity=1,+ )+ red_button = Dot(radius=0.1, stroke_width=0, color="#ff5f56")red_button.shift(LEFT * 0.1 * 3)- yellow_button = Dot(radius=0.1, stroke_width=0, color='#ffbd2e')- green_button = Dot(radius=0.1, stroke_width=0, color='#27c93f')+ yellow_button = Dot(radius=0.1, stroke_width=0, color="#ffbd2e")+ green_button = Dot(radius=0.1, stroke_width=0, color="#27c93f")green_button.shift(RIGHT * 0.1 * 3)buttons = VGroup(red_button, yellow_button, green_button)buttons.shift(- UP * (height / 2 - 0.1 * 2 - 0.05) + LEFT * (width / 2 - 0.1 * 5 - self.corner_radius / 2 - 0.05))+ UP * (height / 2 - 0.1 * 2 - 0.05)+ + LEFT * (width / 2 - 0.1 * 5 - self.corner_radius / 2 - 0.05)+ )self.background_mobject = VGroup(rrect, buttons)x = (height - forground.get_height()) / 2 - 0.1 * 3@@ -103,13 +113,23 @@ class Code(VGroup):self.background_mobject.shift(UP * x)if self.insert_line_no:- VGroup.__init__(self, self.background_mobject, self.line_numbers, *self.code, **kwargs)+ VGroup.__init__(+ self, self.background_mobject, self.line_numbers, *self.code, **kwargs+ )else:- VGroup.__init__(self, self.background_mobject, Dot(fill_opacity=0, stroke_opacity=0), *self.code, **kwargs)+ VGroup.__init__(+ self,+ self.background_mobject,+ Dot(fill_opacity=0, stroke_opacity=0),+ *self.code,+ **kwargs,+ )self.move_to(np.array([0, 0, 0]))- def apply_points_function_about_point(self, func, about_point=None, about_edge=None):+ def apply_points_function_about_point(+ self, func, about_point=None, about_edge=None+ ):if about_point is None:if about_edge is None:about_edge = self.get_corner(UP + LEFT)@@ -131,16 +151,20 @@ class Code(VGroup):if os.path.exists(path):self.file_path = pathreturn- raise IOError("No file matching %s in codes directory" %- self.file_name)+ raise IOError("No file matching %s in codes directory" % self.file_name)def gen_line_numbers(self):line_numbers_array = []for line_no in range(0, self.code_json.__len__()):number = str(self.line_no_from + line_no)line_numbers_array.append(number)- line_numbers = Paragraph(*[i for i in line_numbers_array], line_spacing=self.line_spacing,- alignment="right", font=self.font, stroke_width=self.stroke_width).scale(self.scale_factor)+ line_numbers = Paragraph(+ *[i for i in line_numbers_array],+ line_spacing=self.line_spacing,+ alignment="right",+ font=self.font,+ stroke_width=self.stroke_width,+ ).scale(self.scale_factor)return line_numbersdef gen_colored_lines(self):@@ -150,14 +174,22 @@ class Code(VGroup):for word_index in range(self.code_json[line_no].__len__()):line_str = line_str + self.code_json[line_no][word_index][0]lines_text.append(self.tab_spaces[line_no] * "\t" + line_str)- code = Paragraph(*[i for i in lines_text], line_spacing=self.line_spacing, tab_width=self.tab_width,- alignment="left", font=self.font, stroke_width=self.stroke_width).scale(self.scale_factor)+ code = Paragraph(+ *[i for i in lines_text],+ line_spacing=self.line_spacing,+ tab_width=self.tab_width,+ alignment="left",+ font=self.font,+ stroke_width=self.stroke_width,+ ).scale(self.scale_factor)for line_no in range(code.__len__()):line = code[line_no]line_char_index = self.tab_spaces[line_no]for word_index in range(self.code_json[line_no].__len__()):- line[line_char_index:line_char_index + self.code_json[line_no][word_index][0].__len__()].set_color(- self.code_json[line_no][word_index][1])+ line[+ line_char_index : line_char_index+ + self.code_json[line_no][word_index][0].__len__()+ ].set_color(self.code_json[line_no][word_index][1])line_char_index += self.code_json[line_no][word_index][0].__len__()return code@@ -165,26 +197,43 @@ class Code(VGroup):file = open(self.file_path, "r")code_str = file.read()file.close()- self.html_string = hilite_me(code_str, self.language, {}, self.style, self.insert_line_no,- "border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;")+ self.html_string = hilite_me(+ code_str,+ self.language,+ {},+ self.style,+ self.insert_line_no,+ "border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;",+ )if self.generate_html_file:- os.makedirs(os.path.join("assets", "codes", "generated_html_files"), exist_ok=True)- file = open(os.path.join("assets", "codes", "generated_html_files", self.file_name + ".html"), "w")+ os.makedirs(+ os.path.join("assets", "codes", "generated_html_files"), exist_ok=True+ )+ file = open(+ os.path.join(+ "assets", "codes", "generated_html_files", self.file_name + ".html"+ ),+ "w",+ )file.write(self.html_string)file.close()def gen_code_json(self):- if self.background_color == "#111111" or \- self.background_color == "#272822" or \- self.background_color == "#202020" or \- self.background_color == "#000000":+ if (+ self.background_color == "#111111"+ or self.background_color == "#272822"+ or self.background_color == "#202020"+ or self.background_color == "#000000"+ ):self.default_color = "#ffffff"else:self.default_color = "#000000"for i in range(3, -1, -1):self.html_string = self.html_string.replace("</" + " " * i, "</")for i in range(10, -1, -1):- self.html_string = self.html_string.replace("</span>" + " " * i, " " * i + "</span>")+ self.html_string = self.html_string.replace(+ "</span>" + " " * i, " " * i + "</span>"+ )self.html_string = self.html_string.replace("background-color:", "background:")if self.insert_line_no:@@ -195,9 +244,9 @@ class Code(VGroup):self.html_string = self.html_string[start_point:]# print(self.html_string)lines = self.html_string.split("\n")- lines = lines[0:lines.__len__() - 2]+ lines = lines[0 : lines.__len__() - 2]start_point = lines[0].find(">")- lines[0] = lines[0][start_point + 1:]+ lines[0] = lines[0][start_point + 1 :]# print(lines)self.code_json = []self.tab_spaces = []@@ -211,16 +260,28 @@ class Code(VGroup):if lines[line_index].startswith(self.indentation_char):start_point = lines[line_index].find("<")starting_string = lines[line_index][:start_point]- indentation_char_count = lines[line_index][:start_point].count(self.indentation_char)- if starting_string.__len__() != indentation_char_count * self.indentation_char.__len__():- lines[line_index] = "\t" * indentation_char_count + starting_string[starting_string.rfind(- self.indentation_char) + self.indentation_char.__len__():] + \- lines[line_index][start_point:]+ indentation_char_count = lines[line_index][:start_point].count(+ self.indentation_char+ )+ if (+ starting_string.__len__()+ != indentation_char_count * self.indentation_char.__len__()+ ):+ lines[line_index] = (+ "\t" * indentation_char_count+ + starting_string[+ starting_string.rfind(self.indentation_char)+ + self.indentation_char.__len__() :+ ]+ + lines[line_index][start_point:]+ )else:- lines[line_index] = "\t" * indentation_char_count + lines[line_index][start_point:]+ lines[line_index] = (+ "\t" * indentation_char_count + lines[line_index][start_point:]+ )indentation_char_count = 0- while lines[line_index][indentation_char_count] == '\t':+ while lines[line_index][indentation_char_count] == "\t":indentation_char_count = indentation_char_count + 1self.tab_spaces.append(indentation_char_count)# print(lines[line_index])@@ -233,11 +294,13 @@ class Code(VGroup):color = self.default_colorelse:starti = words[word_index][color_index:].find("#")- color = words[word_index][color_index + starti:color_index + starti + 7]+ color = words[word_index][+ color_index + starti : color_index + starti + 7+ ]start_point = words[word_index].find(">")end_point = words[word_index].find("</span>")- text = words[word_index][start_point + 1:end_point]+ text = words[word_index][start_point + 1 : end_point]text = html.unescape(text)if text != "":# print(text, "'" + color + "'")@@ -258,13 +321,25 @@ class Code(VGroup):if words[i][k] == "\t" and starti == -1:continueelse:- if starti == -1: starti = k+ if starti == -1:+ starti = ktemp = temp + words[i][k]if temp != "":if i != words.__len__() - 1:- temp = '<span style="color:' + self.default_color + '">' + words[i][starti:j] + "</span>"+ temp = (+ '<span style="color:'+ + self.default_color+ + '">'+ + words[i][starti:j]+ + "</span>"+ )else:- temp = '<span style="color:' + self.default_color + '">' + words[i][starti:j]+ temp = (+ '<span style="color:'+ + self.default_color+ + '">'+ + words[i][starti:j]+ )temp = temp + words[i][j:]words[i] = tempif words[i] != "":@@ -273,16 +348,18 @@ class Code(VGroup):def hilite_me(code, lexer, options, style, linenos, divstyles):- lexer = lexer or 'python'- style = style or 'colorful'- defstyles = 'overflow:auto;width:auto;'+ lexer = lexer or "python"+ style = style or "colorful"+ defstyles = "overflow:auto;width:auto;"- formatter = HtmlFormatter(style=style,- linenos=False,- noclasses=True,- cssclass='',- cssstyles=defstyles + divstyles,- prestyles='margin: 0')+ formatter = HtmlFormatter(+ style=style,+ linenos=False,+ noclasses=True,+ cssclass="",+ cssstyles=defstyles + divstyles,+ prestyles="margin: 0",+ )html = highlight(code, get_lexer_by_name(lexer, **options), formatter)if linenos:html = insert_line_numbers(html)@@ -291,20 +368,23 @@ def hilite_me(code, lexer, options, style, linenos, divstyles):def get_default_style():- return 'border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;'+ return "border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"def insert_line_numbers(html):- match = re.search('(<pre[^>]*>)(.*)(</pre>)', html, re.DOTALL)- if not match: return html+ match = re.search("(<pre[^>]*>)(.*)(</pre>)", html, re.DOTALL)+ if not match:+ return htmlpre_open = match.group(1)pre = match.group(2)pre_close = match.group(3)- html = html.replace(pre_close, '</pre></td></tr></table>')- numbers = range(1, pre.count('\n') + 1)- format = '%' + str(len(str(numbers[-1]))) + 'i'- lines = '\n'.join(format % i for i in numbers)- html = html.replace(pre_open, '<table><tr><td>' + pre_open + lines + '</pre></td><td>' + pre_open)- return html\ No newline at end of file+ html = html.replace(pre_close, "</pre></td></tr></table>")+ numbers = range(1, pre.count("\n") + 1)+ format = "%" + str(len(str(numbers[-1]))) + "i"+ lines = "\n".join(format % i for i in numbers)+ html = html.replace(+ pre_open, "<table><tr><td>" + pre_open + lines + "</pre></td><td>" + pre_open+ )+ return htmldiff --git a/manim/mobject/svg/drawings.py b/manim/mobject/svg/drawings.pyindex 96f7c2f50..67dd69465 100644--- a/manim/mobject/svg/drawings.py+++ b/manim/mobject/svg/drawings.py@@ -79,10 +79,7 @@ class Speedometer(VMobject):def generate_points(self):start_angle = np.pi / 2 + self.arc_angle / 2end_angle = np.pi / 2 - self.arc_angle / 2- self.add(Arc(- start_angle=start_angle,- angle=-self.arc_angle- ))+ self.add(Arc(start_angle=start_angle, angle=-self.arc_angle))tick_angle_range = np.linspace(start_angle, end_angle, self.num_ticks)for index, angle in enumerate(tick_angle_range):vect = rotate_vector(RIGHT, angle)@@ -93,10 +90,12 @@ class Speedometer(VMobject):self.add(tick, label)needle = Polygon(- LEFT, UP, RIGHT,+ LEFT,+ UP,+ RIGHT,stroke_width=0,fill_opacity=1,- fill_color=self.needle_color+ fill_color=self.needle_color,)needle.stretch_to_fit_width(self.needle_width)needle.stretch_to_fit_height(self.needle_height)@@ -116,9 +115,7 @@ class Speedometer(VMobject):return self.needle.get_anchors()[1]def get_needle_angle(self):- return angle_of_vector(- self.get_needle_tip() - self.get_center()- )+ return angle_of_vector(self.get_needle_tip() - self.get_center())def rotate_needle(self, angle):self.needle.rotate(angle, about_point=self.get_center())@@ -146,7 +143,7 @@ class AoPSLogo(SVGMobject):index_lists = [(10, 11, 12, 13, 14, 21, 22, 23, 24, 27, 28, 29, 30),(0, 1, 2, 3, 4, 15, 16, 17, 26),- (5, 6, 7, 8, 9, 18, 19, 20, 25)+ (5, 6, 7, 8, 9, 18, 19, 20, 25),]for color, index_list in zip(colors, index_lists):for i in index_list:@@ -173,9 +170,9 @@ class PartyHat(SVGMobject):SVGMobject.__init__(self, **kwargs)self.set_height(self.height)- self.frills = VGroup(*self[:self.NUM_FRILLS])+ self.frills = VGroup(*self[: self.NUM_FRILLS])self.cone = self[self.NUM_FRILLS]- self.dots = VGroup(*self[self.NUM_FRILLS + 1:])+ self.dots = VGroup(*self[self.NUM_FRILLS + 1 :])self.frills.set_color_by_gradient(*self.frills_colors)self.cone.set_color(self.cone_color)@@ -212,13 +209,14 @@ class Laptop(VGroup):body.sort(lambda p: p[2])body[-1].set_fill(self.body_color)screen_plate = body.copy()- keyboard = VGroup(*[- VGroup(*[- Square(**self.key_color_kwargs)- for x in range(12 - y % 2)- ]).arrange(RIGHT, buff=SMALL_BUFF)- for y in range(4)- ]).arrange(DOWN, buff=MED_SMALL_BUFF)+ keyboard = VGroup(+ *[+ VGroup(+ *[Square(**self.key_color_kwargs) for x in range(12 - y % 2)]+ ).arrange(RIGHT, buff=SMALL_BUFF)+ for y in range(4)+ ]+ ).arrange(DOWN, buff=MED_SMALL_BUFF)keyboard.stretch_to_fit_width(self.keyboard_width_to_body_width * body.get_width(),)@@ -229,21 +227,15 @@ class Laptop(VGroup):keyboard.shift(MED_SMALL_BUFF * UP)body.add(keyboard)- screen_plate.stretch(self.screen_thickness /- self.body_dimensions[2], dim=2)- screen = Rectangle(- stroke_width=0,- fill_color=BLACK,- fill_opacity=1,- )+ screen_plate.stretch(self.screen_thickness / self.body_dimensions[2], dim=2)+ screen = Rectangle(stroke_width=0, fill_color=BLACK, fill_opacity=1,)screen.replace(screen_plate, stretch=True)screen.scale_in_place(self.screen_width_to_screen_plate_width)screen.next_to(screen_plate, OUT, buff=0.1 * SMALL_BUFF)screen_plate.add(screen)screen_plate.next_to(body, UP, buff=0)screen_plate.rotate(- self.open_angle, RIGHT,- about_point=screen_plate.get_bottom()+ self.open_angle, RIGHT, about_point=screen_plate.get_bottom())self.screen_plate = screen_plateself.screen = screen@@ -252,7 +244,7 @@ class Laptop(VGroup):body.get_corner(UP + LEFT + OUT),body.get_corner(UP + RIGHT + OUT),color=BLACK,- stroke_width=2+ stroke_width=2,)self.axis = axis@@ -280,7 +272,7 @@ class PatreonLogo(SVGMobject):class VideoIcon(SVGMobject):CONFIG = {"file_name": "video_icon",- "width": config['frame_width'] / 12.,+ "width": config["frame_width"] / 12.0,}def __init__(self, **kwargs):@@ -302,7 +294,7 @@ class VideoSeries(VGroup):videos = [VideoIcon() for x in range(self.num_videos)]VGroup.__init__(self, *videos, **kwargs)self.arrange()- self.set_width(config['frame_width'] - config['med_large_buff'])+ self.set_width(config["frame_width"] - config["med_large_buff"])self.set_color_by_gradient(*self.gradient_colors)@@ -330,25 +322,17 @@ class Clock(VGroup):circle = Circle(color=WHITE)ticks = []for x in range(12):- alpha = x / 12.- point = complex_to_R3(- np.exp(2 * np.pi * alpha * complex(0, 1))- )+ alpha = x / 12.0+ point = complex_to_R3(np.exp(2 * np.pi * alpha * complex(0, 1)))length = 0.2 if x % 3 == 0 else 0.1- ticks.append(- Line(point, (1 - length) * point)- )+ ticks.append(Line(point, (1 - length) * point))self.hour_hand = Line(ORIGIN, 0.3 * UP)self.minute_hand = Line(ORIGIN, 0.6 * UP)# for hand in self.hour_hand, self.minute_hand:# #Balance out where the center is# hand.add(VectorizedPoint(-hand.get_end()))- VGroup.__init__(- self, circle,- self.hour_hand, self.minute_hand,- *ticks- )+ VGroup.__init__(self, circle, self.hour_hand, self.minute_hand, *ticks)class ClockPassesTime(Animation):@@ -360,22 +344,15 @@ class ClockPassesTime(Animation):def __init__(self, clock, **kwargs):digest_config(self, kwargs)- assert(isinstance(clock, Clock))- rot_kwargs = {- "axis": OUT,- "about_point": clock.get_center()- }+ assert isinstance(clock, Clock)+ rot_kwargs = {"axis": OUT, "about_point": clock.get_center()}hour_radians = -self.hours_passed * 2 * np.pi / 12self.hour_rotation = Rotating(- clock.hour_hand,- radians=hour_radians,- **rot_kwargs+ clock.hour_hand, radians=hour_radians, **rot_kwargs)self.hour_rotation.begin()self.minute_rotation = Rotating(- clock.minute_hand,- radians=12 * hour_radians,- **rot_kwargs+ clock.minute_hand, radians=12 * hour_radians, **rot_kwargs)self.minute_rotation.begin()Animation.__init__(self, clock, **kwargs)@@ -392,7 +369,7 @@ class Bubble(SVGMobject):"content_scale_factor": 0.75,"height": 5,"width": 8,- "bubble_center_adjustment_factor": 1. / 8,+ "bubble_center_adjustment_factor": 1.0 / 8,"file_name": None,"fill_color": BLACK,"fill_opacity": 0.8,@@ -414,7 +391,7 @@ class Bubble(SVGMobject):self.stretch_to_fit_width(self.width)if self.direction[0] > 0:self.flip()- self.direction_was_specified = ("direction" in kwargs)+ self.direction_was_specified = "direction" in kwargsself.content = Mobject()def get_tip(self):@@ -453,9 +430,7 @@ class Bubble(SVGMobject):scaled_width = self.content_scale_factor * self.get_width()if mobject.get_width() > scaled_width:mobject.set_width(scaled_width)- mobject.shift(- self.get_bubble_center() - mobject.get_center()- )+ mobject.shift(self.get_bubble_center() - mobject.get_center())return mobjectdef add_content(self, mobject):@@ -484,17 +459,11 @@ class Bubble(SVGMobject):class SpeechBubble(Bubble):- CONFIG = {- "file_name": "Bubbles_speech.svg",- "height": 4- }+ CONFIG = {"file_name": "Bubbles_speech.svg", "height": 4}class DoubleSpeechBubble(Bubble):- CONFIG = {- "file_name": "Bubbles_double_speech.svg",- "height": 4- }+ CONFIG = {"file_name": "Bubbles_double_speech.svg", "height": 4}class ThoughtBubble(Bubble):@@ -504,9 +473,7 @@ class ThoughtBubble(Bubble):def __init__(self, **kwargs):Bubble.__init__(self, **kwargs)- self.submobjects.sort(- key=lambda m: m.get_bottom()[1]- )+ self.submobjects.sort(key=lambda m: m.get_bottom()[1])def make_green_screen(self):self.submobjects[-1].set_fill(GREEN_SCREEN, opacity=1)@@ -549,9 +516,7 @@ class Car(SVGMobject):self.add_treds_to_tires()def move_to(self, point_or_mobject):- vect = rotate_vector(- UP + LEFT, self.orientation_line.get_angle()- )+ vect = rotate_vector(UP + LEFT, self.orientation_line.get_angle())self.next_to(point_or_mobject, vect, buff=0)return self@@ -568,9 +533,7 @@ class Car(SVGMobject):radius = tire.get_width() / 2center = tire.get_center()tred = Line(- 0.7 * radius * RIGHT, 1.1 * radius * RIGHT,- stroke_width=2,- color=BLACK+ 0.7 * radius * RIGHT, 1.1 * radius * RIGHT, stroke_width=2, color=BLACK)tred.rotate(PI / 5, about_point=tred.get_end())for theta in np.arange(0, 2 * np.pi, np.pi / 4):@@ -603,10 +566,7 @@ class VectorizedEarth(SVGMobject):def __init__(self, **kwargs):SVGMobject.__init__(self, **kwargs)circle = Circle(- stroke_width=3,- stroke_color=GREEN,- fill_opacity=1,- fill_color=BLUE_C,+ stroke_width=3, stroke_color=GREEN, fill_opacity=1, fill_color=BLUE_C,)circle.replace(self)self.add_to_back(circle)@@ -618,18 +578,8 @@ class Logo(VMobject):"outer_radius": 2.0,"iris_background_blue": "#74C0E3","iris_background_brown": "#8C6239",- "blue_spike_colors": [- "#528EA3",- "#3E6576",- "#224C5B",- BLACK,- ],- "brown_spike_colors": [- "#754C24",- "#603813",- "#42210b",- BLACK,- ],+ "blue_spike_colors": ["#528EA3", "#3E6576", "#224C5B", BLACK,],+ "brown_spike_colors": ["#754C24", "#603813", "#42210b", BLACK,],"n_spike_layers": 4,"n_spikes": 28,"spike_angle": TAU / 28,@@ -660,25 +610,17 @@ class Logo(VMobject):fill_opacity=1,stroke_width=0,)- self.iris_background = VGroup(- blue_iris_back,- brown_iris_back,- )+ self.iris_background = VGroup(blue_iris_back, brown_iris_back,)self.add(self.iris_background)def add_spikes(self):layers = VGroup()radii = np.linspace(- self.outer_radius,- self.pupil_radius,- self.n_spike_layers,- endpoint=False,+ self.outer_radius, self.pupil_radius, self.n_spike_layers, endpoint=False,)radii[:2] = radii[1::-1] # Swap first twoif self.n_spike_layers > 2:- radii[-1] = interpolate(- radii[-1], self.pupil_radius, 0.25- )+ radii[-1] = interpolate(radii[-1], self.pupil_radius, 0.25)for radius in radii:tip_angle = self.spike_angle@@ -698,40 +640,32 @@ class Logo(VMobject):n_spikes = self.n_spikesfull_spikes = [- triangle.copy().rotate(- -angle,- about_point=ORIGIN- )- for angle in np.linspace(- 0, TAU, n_spikes, endpoint=False- )+ triangle.copy().rotate(-angle, about_point=ORIGIN)+ for angle in np.linspace(0, TAU, n_spikes, endpoint=False)]index = (3 * n_spikes) // 4if radius == radii[0]:layer = VGroup(*full_spikes)- layer.rotate(- -TAU / n_spikes / 2,- about_point=ORIGIN- )+ layer.rotate(-TAU / n_spikes / 2, about_point=ORIGIN)layer.brown_index = indexelse:half_spikes = [right_half_triangle.copy(),- left_half_triangle.copy().rotate(- 90 * DEGREES, about_point=ORIGIN,- ),+ left_half_triangle.copy().rotate(90 * DEGREES, about_point=ORIGIN,),right_half_triangle.copy().rotate(90 * DEGREES, about_point=ORIGIN,),- left_half_triangle.copy()+ left_half_triangle.copy(),]- layer = VGroup(*it.chain(- half_spikes[:1],- full_spikes[1:index],- half_spikes[1:3],- full_spikes[index + 1:],- half_spikes[3:],- ))+ layer = VGroup(+ *it.chain(+ half_spikes[:1],+ full_spikes[1:index],+ half_spikes[1:3],+ full_spikes[index + 1 :],+ half_spikes[3:],+ )+ )layer.brown_index = index + 1layers.add(layer)@@ -761,16 +695,16 @@ class Logo(VMobject):def cut_pupil(self):pupil = self.pupilcenter = pupil.get_center()- new_pupil = VGroup(*[- pupil.copy().pointwise_become_partial(pupil, a, b)- for (a, b) in [(0.25, 1), (0, 0.25)]- ])+ new_pupil = VGroup(+ *[+ pupil.copy().pointwise_become_partial(pupil, a, b)+ for (a, b) in [(0.25, 1), (0, 0.25)]+ ]+ )for sector in new_pupil:- sector.add_cubic_bezier_curve_to([- sector.points[-1],- *[center] * 3,- *[sector.points[0]] * 2- ])+ sector.add_cubic_bezier_curve_to(+ [sector.points[-1], *[center] * 3, *[sector.points[0]] * 2]+ )self.remove(pupil)self.add(new_pupil)self.pupil = new_pupil@@ -785,18 +719,12 @@ class Logo(VMobject):# circle.move_to(self)blue_part = VGroup(self.iris_background[0],- *[- layer[:layer.brown_index]- for layer in self.spike_layers- ],+ *[layer[: layer.brown_index] for layer in self.spike_layers],self.pupil[0],)brown_part = VGroup(self.iris_background[1],- *[- layer[layer.brown_index:]- for layer in self.spike_layers- ],+ *[layer[layer.brown_index :] for layer in self.spike_layers],self.pupil[1],)return blue_part, brown_part@@ -807,11 +735,14 @@ class DeckOfCards(VGroup):def __init__(self, **kwargs):possible_values = list(map(str, list(range(1, 11)))) + ["J", "Q", "K"]possible_suits = ["hearts", "diamonds", "spades", "clubs"]- VGroup.__init__(self, *[- PlayingCard(value=value, suit=suit, **kwargs)- for value in possible_values- for suit in possible_suits- ])+ VGroup.__init__(+ self,+ *[+ PlayingCard(value=value, suit=suit, **kwargs)+ for value in possible_values+ for suit in possible_suits+ ],+ )class PlayingCard(VGroup):@@ -834,14 +765,16 @@ class PlayingCard(VGroup):VGroup.__init__(self, key=key, **kwargs)def generate_points(self):- self.add(Rectangle(- height=self.height,- width=self.height / self.height_to_width,- stroke_color=WHITE,- stroke_width=2,- fill_color=self.color,- fill_opacity=1,- ))+ self.add(+ Rectangle(+ height=self.height,+ width=self.height / self.height_to_width,+ stroke_color=WHITE,+ stroke_width=2,+ fill_color=self.color,+ fill_opacity=1,+ )+ )if self.turned_over:self.set_fill(DARK_GREY)self.set_stroke(LIGHT_GREY)@@ -885,10 +818,9 @@ class PlayingCard(VGroup):suit = self.suitif suit is None:if self.key is not None:- suit = dict([- (string.upper(s[0]), s)- for s in self.possible_suits- ])[string.upper(self.key[-1])]+ suit = dict([(string.upper(s[0]), s) for s in self.possible_suits])[+ string.upper(self.key[-1])+ ]else:suit = random.choice(self.possible_suits)if suit not in self.possible_suits:@@ -913,48 +845,30 @@ class PlayingCard(VGroup):def get_number_design(self, value, symbol):num = int(value)- n_rows = {- 2: 2,- 3: 3,- 4: 2,- 5: 2,- 6: 3,- 7: 3,- 8: 3,- 9: 4,- 10: 4,- }[num]+ n_rows = {2: 2, 3: 3, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 4, 10: 4,}[num]n_cols = 1 if num in [2, 3] else 2- insertion_indices = {- 5: [0],- 7: [0],- 8: [0, 1],- 9: [1],- 10: [0, 2],- }.get(num, [])+ insertion_indices = {5: [0], 7: [0], 8: [0, 1], 9: [1], 10: [0, 2],}.get(+ num, []+ )top = self.get_top() + symbol.get_height() * DOWNbottom = self.get_bottom() + symbol.get_height() * UPcolumn_points = [- interpolate(top, bottom, alpha)- for alpha in np.linspace(0, 1, n_rows)+ interpolate(top, bottom, alpha) for alpha in np.linspace(0, 1, n_rows)]- design = VGroup(*[- symbol.copy().move_to(point)- for point in column_points- ])+ design = VGroup(*[symbol.copy().move_to(point) for point in column_points])if n_cols == 2:space = 0.2 * self.get_width()column_copy = design.copy().shift(space * RIGHT)design.shift(space * LEFT)design.add(*column_copy)- design.add(*[- symbol.copy().move_to(- center_of_mass(column_points[i:i + 2])- )- for i in insertion_indices- ])+ design.add(+ *[+ symbol.copy().move_to(center_of_mass(column_points[i : i + 2]))+ for i in insertion_indices+ ]+ )for symbol in design:if symbol.get_center()[1] < self.get_center()[1]:symbol.rotate_in_place(np.pi)@@ -970,21 +884,15 @@ class PlayingCard(VGroup):value_mob.set_width(width)value_mob.stretch_to_fit_height(height)value_mob.next_to(- self.get_corner(UP + LEFT), DOWN + RIGHT,- buff=MED_LARGE_BUFF * width+ self.get_corner(UP + LEFT), DOWN + RIGHT, buff=MED_LARGE_BUFF * width)value_mob.set_color(symbol.get_color())corner_symbol = symbol.copy()corner_symbol.set_width(width)- corner_symbol.next_to(- value_mob, DOWN,- buff=MED_SMALL_BUFF * width- )+ corner_symbol.next_to(value_mob, DOWN, buff=MED_SMALL_BUFF * width)corner_group = VGroup(value_mob, corner_symbol)opposite_corner_group = corner_group.copy()- opposite_corner_group.rotate(- np.pi, about_point=self.get_center()- )+ opposite_corner_group.rotate(np.pi, about_point=self.get_center())return VGroup(corner_group, opposite_corner_group)diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.pyindex adc3e6195..2a0e864e9 100644--- a/manim/mobject/svg/svg_mobject.py+++ b/manim/mobject/svg/svg_mobject.py@@ -20,11 +20,7 @@ from ...utils.config_ops import digest_localsdef string_to_numbers(num_string):num_string = num_string.replace("-", ",-")num_string = num_string.replace("e,-", "e-")- return [- float(s)- for s in re.split("[ ,]", num_string)- if s != ""- ]+ return [float(s) for s in re.split("[ ,]", num_string) if s != ""]class SVGMobject(VMobject):@@ -60,8 +56,7 @@ class SVGMobject(VMobject):if os.path.exists(path):self.file_path = pathreturn- raise IOError("No file matching %s in image directory" %- self.file_name)+ raise IOError("No file matching %s in image directory" % self.file_name)def generate_points(self):doc = minidom.parse(self.file_path)@@ -78,28 +73,27 @@ class SVGMobject(VMobject):result = []if not isinstance(element, minidom.Element):return result- if element.tagName == 'defs':+ if element.tagName == "defs":self.update_ref_to_element(element)- elif element.tagName == 'style':+ elif element.tagName == "style":pass # TODO, handle style- elif element.tagName in ['g', 'svg', 'symbol']:- result += it.chain(*[- self.get_mobjects_from(child)- for child in element.childNodes- ])- elif element.tagName == 'path':- temp = element.getAttribute('d')- if temp != '':+ elif element.tagName in ["g", "svg", "symbol"]:+ result += it.chain(+ *[self.get_mobjects_from(child) for child in element.childNodes]+ )+ elif element.tagName == "path":+ temp = element.getAttribute("d")+ if temp != "":result.append(self.path_string_to_mobject(temp))- elif element.tagName == 'use':+ elif element.tagName == "use":result += self.use_to_mobjects(element)- elif element.tagName == 'rect':+ elif element.tagName == "rect":result.append(self.rect_to_mobject(element))- elif element.tagName == 'circle':+ elif element.tagName == "circle":result.append(self.circle_to_mobject(element))- elif element.tagName == 'ellipse':+ elif element.tagName == "ellipse":result.append(self.ellipse_to_mobject(element))- elif element.tagName in ['polygon', 'polyline']:+ elif element.tagName in ["polygon", "polyline"]:result.append(self.polygon_to_mobject(element))else:pass # TODO@@ -125,15 +119,12 @@ class SVGMobject(VMobject):if ref not in self.ref_to_element:warnings.warn("%s not recognized" % ref)return VGroup()- return self.get_mobjects_from(- self.ref_to_element[ref]- )+ return self.get_mobjects_from(self.ref_to_element[ref])def attribute_to_float(self, attr):- stripped_attr = "".join([- char for char in attr- if char in string.digits + "." + "-"- ])+ stripped_attr = "".join(+ [char for char in attr if char in string.digits + "." + "-"]+ )return float(stripped_attr)def polygon_to_mobject(self, polygon_element):@@ -148,9 +139,7 @@ class SVGMobject(VMobject):def circle_to_mobject(self, circle_element):x, y, r = [- self.attribute_to_float(- circle_element.getAttribute(key)- )+ self.attribute_to_float(circle_element.getAttribute(key))if circle_element.hasAttribute(key)else 0.0for key in ("cx", "cy", "r")@@ -159,9 +148,7 @@ class SVGMobject(VMobject):def ellipse_to_mobject(self, circle_element):x, y, rx, ry = [- self.attribute_to_float(- circle_element.getAttribute(key)- )+ self.attribute_to_float(circle_element.getAttribute(key))if circle_element.hasAttribute(key)else 0.0for key in ("cx", "cy", "rx", "ry")@@ -175,12 +162,16 @@ class SVGMobject(VMobject):corner_radius = rect_element.getAttribute("rx")# input preprocessing- if fill_color in ["", "none", "#FFF", "#FFFFFF"] or Color(fill_color) == Color(WHITE):+ if fill_color in ["", "none", "#FFF", "#FFFFFF"] or Color(fill_color) == Color(+ WHITE+ ):opacity = 0fill_color = BLACK # shdn't be necessary but avoids error msgsif fill_color in ["#000", "#000000"]:fill_color = WHITE- if stroke_color in ["", "none", "#FFF", "#FFFFFF"] or Color(stroke_color) == Color(WHITE):+ if stroke_color in ["", "none", "#FFF", "#FFFFFF"] or Color(+ stroke_color+ ) == Color(WHITE):stroke_width = 0stroke_color = BLACKif stroke_color in ["#000", "#000000"]:@@ -195,30 +186,22 @@ class SVGMobject(VMobject):if corner_radius == 0:mob = Rectangle(- width=self.attribute_to_float(- rect_element.getAttribute("width")- ),- height=self.attribute_to_float(- rect_element.getAttribute("height")- ),+ width=self.attribute_to_float(rect_element.getAttribute("width")),+ height=self.attribute_to_float(rect_element.getAttribute("height")),stroke_width=stroke_width,stroke_color=stroke_color,fill_color=fill_color,- fill_opacity=opacity+ fill_opacity=opacity,)else:mob = RoundedRectangle(- width=self.attribute_to_float(- rect_element.getAttribute("width")- ),- height=self.attribute_to_float(- rect_element.getAttribute("height")- ),+ width=self.attribute_to_float(rect_element.getAttribute("width")),+ height=self.attribute_to_float(rect_element.getAttribute("height")),stroke_width=stroke_width,stroke_color=stroke_color,fill_color=fill_color,fill_opacity=opacity,- corner_radius=corner_radius+ corner_radius=corner_radius,)mob.shift(mob.get_center() - mob.get_corner(UP + LEFT))@@ -227,21 +210,21 @@ class SVGMobject(VMobject):def handle_transforms(self, element, mobject):x, y = 0, 0try:- x = self.attribute_to_float(element.getAttribute('x'))+ x = self.attribute_to_float(element.getAttribute("x"))# Flip y- y = -self.attribute_to_float(element.getAttribute('y'))+ y = -self.attribute_to_float(element.getAttribute("y"))mobject.shift(x * RIGHT + y * UP)except:pass- transform = element.getAttribute('transform')+ transform = element.getAttribute("transform")try: # transform matrixprefix = "matrix("suffix = ")"if not transform.startswith(prefix) or not transform.endswith(suffix):raise Exception()- transform = transform[len(prefix):-len(suffix)]+ transform = transform[len(prefix) : -len(suffix)]transform = string_to_numbers(transform)transform = np.array(transform).reshape([3, 2])x = transform[2][0]@@ -262,7 +245,7 @@ class SVGMobject(VMobject):suffix = ")"if not transform.startswith(prefix) or not transform.endswith(suffix):raise Exception()- transform = transform[len(prefix):-len(suffix)]+ transform = transform[len(prefix) : -len(suffix)]scale_values = string_to_numbers(transform)if len(scale_values) == 2:scale_x, scale_y = scale_values@@ -278,7 +261,7 @@ class SVGMobject(VMobject):suffix = ")"if not transform.startswith(prefix) or not transform.endswith(suffix):raise Exception()- transform = transform[len(prefix):-len(suffix)]+ transform = transform[len(prefix) : -len(suffix)]x, y = string_to_numbers(transform)mobject.shift(x * RIGHT + y * DOWN)except:@@ -298,14 +281,16 @@ class SVGMobject(VMobject):all_childNodes_have_id = []if not isinstance(element, minidom.Element):return- if element.hasAttribute('id'):+ if element.hasAttribute("id"):return [element]for e in element.childNodes:all_childNodes_have_id.append(self.get_all_childNodes_have_id(e))return self.flatten([e for e in all_childNodes_have_id if e])def update_ref_to_element(self, defs):- new_refs = dict([(e.getAttribute('id'), e) for e in self.get_all_childNodes_have_id(defs)])+ new_refs = dict(+ [(e.getAttribute("id"), e) for e in self.get_all_childNodes_have_id(defs)]+ )self.ref_to_element.update(new_refs)def move_into_position(self):@@ -340,10 +325,12 @@ class VMobjectFromSVGPathstring(VMobject):def generate_points(self):pattern = "[%s]" % ("".join(self.get_path_commands()))- pairs = list(zip(- re.findall(pattern, self.path_string),- re.split(pattern, self.path_string)[1:]- ))+ pairs = list(+ zip(+ re.findall(pattern, self.path_string),+ re.split(pattern, self.path_string)[1:],+ )+ )# Which mobject should new points be added toself = selffor command, coord_string in pairs:@@ -415,9 +402,9 @@ class VMobjectFromSVGPathstring(VMobject):# Add subsequent offset points relatively.for i in range(3, len(new_points), 3):if isLower:- new_points[i:i + 3] -= points[-1]- new_points[i:i + 3] += new_points[i - 1]- self.add_cubic_bezier_curve_to(*new_points[i:i+3])+ new_points[i : i + 3] -= points[-1]+ new_points[i : i + 3] += new_points[i - 1]+ self.add_cubic_bezier_curve_to(*new_points[i : i + 3])def string_to_points(self, coord_string):numbers = string_to_numbers(coord_string)diff --git a/manim/mobject/svg/tex_mobject.py b/manim/mobject/svg/tex_mobject.pyindex 242f7bd41..c63824387 100644--- a/manim/mobject/svg/tex_mobject.py+++ b/manim/mobject/svg/tex_mobject.py@@ -17,6 +17,7 @@ TEX_MOB_SCALE_FACTOR = 0.05class TexSymbol(VMobjectFromSVGPathstring):"""Purely a renaming of VMobjectFromSVGPathstring."""+pass@@ -35,12 +36,9 @@ class SingleStringTexMobject(SVGMobject):def __init__(self, tex_string, **kwargs):digest_config(self, kwargs)- assert(isinstance(tex_string, str))+ assert isinstance(tex_string, str)self.tex_string = tex_string- file_name = tex_to_svg_file(- self.get_modified_expression(tex_string),- self.type- )+ file_name = tex_to_svg_file(self.get_modified_expression(tex_string), self.type)SVGMobject.__init__(self, file_name=file_name, **kwargs)if self.height is None:self.scale(TEX_MOB_SCALE_FACTOR)@@ -55,17 +53,20 @@ class SingleStringTexMobject(SVGMobject):def modify_special_strings(self, tex):tex = self.remove_stray_braces(tex)- should_add_filler = reduce(op.or_, [- # Fraction line needs something to be over- tex == "\\over",- tex == "\\overline",- # Makesure sqrt has overbar- tex == "\\sqrt",- # Need to add blank subscript or superscript- tex.endswith("_"),- tex.endswith("^"),- tex.endswith("dot"),- ])+ should_add_filler = reduce(+ op.or_,+ [+ # Fraction line needs something to be over+ tex == "\\over",+ tex == "\\overline",+ # Makesure sqrt has overbar+ tex == "\\sqrt",+ # Need to add blank subscript or superscript+ tex.endswith("_"),+ tex.endswith("^"),+ tex.endswith("dot"),+ ],+ )if should_add_filler:filler = "{\\quad}"tex += filler@@ -82,10 +83,7 @@ class SingleStringTexMobject(SVGMobject):# Handle imbalanced \left and \rightnum_lefts, num_rights = [- len([- s for s in tex.split(substr)[1:]- if s and s[0] in "(){}[]|.\\"- ])+ len([s for s in tex.split(substr)[1:] if s and s[0] in "(){}[]|.\\"])for substr in ("\\left", "\\right")]if num_lefts != num_rights:@@ -106,10 +104,7 @@ class SingleStringTexMobject(SVGMobject):"""Makes TexMobject resiliant to unmatched { at start"""- num_lefts, num_rights = [- tex.count(char)- for char in "{}"- ]+ num_lefts, num_rights = [tex.count(char) for char in "{}"]while num_rights > num_lefts:tex = "{" + texnum_lefts += 1@@ -153,16 +148,15 @@ class TexMobject(SingleStringTexMobject):def break_up_tex_strings(self, tex_strings):substrings_to_isolate = op.add(- self.substrings_to_isolate,- list(self.tex_to_color_map.keys())+ self.substrings_to_isolate, list(self.tex_to_color_map.keys()))split_list = split_string_list_to_isolate_substrings(tex_strings, *substrings_to_isolate)- if self.arg_separator == ' ':+ if self.arg_separator == " ":split_list = [str(x).strip() for x in split_list]- #split_list = list(map(str.strip, split_list))- split_list = [s for s in split_list if s != '']+ # split_list = list(map(str.strip, split_list))+ split_list = [s for s in split_list if s != ""]return split_listdef break_up_by_substrings(self):@@ -219,7 +213,7 @@ class TexMobject(SingleStringTexMobject):for texs, color in list(texs_to_color_map.items()):try:# If the given key behaves like tex_strings- texs + ''+ texs + ""self.set_color_by_tex(texs, color, **kwargs)except TypeError:# If the given key is a tuple@@ -238,9 +232,7 @@ class TexMobject(SingleStringTexMobject):return self.index_of_part(part)def sort_alphabetically(self):- self.submobjects.sort(- key=lambda m: m.get_tex_string()- )+ self.submobjects.sort(key=lambda m: m.get_tex_string())class TextMobject(TexMobject):@@ -266,11 +258,7 @@ class BulletedList(TextMobject):dot = TexMobject("\\cdot").scale(self.dot_scale_factor)dot.next_to(part[0], LEFT, SMALL_BUFF)part.add_to_back(dot)- self.arrange(- DOWN,- aligned_edge=LEFT,- buff=self.buff- )+ self.arrange(DOWN, aligned_edge=LEFT, buff=self.buff)def fade_all_but(self, index_or_string, opacity=0.5):arg = index_or_string@@ -304,7 +292,7 @@ class Title(TextMobject):CONFIG = {"scale_factor": 1,"include_underline": True,- "underline_width": config['frame_width'] - 2,+ "underline_width": config["frame_width"] - 2,# This will override underline_width"match_underline_width_to_text": False,"underline_buff": MED_SMALL_BUFF,diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.pyindex 386f9433c..26106f18a 100644--- a/manim/mobject/svg/text_mobject.py+++ b/manim/mobject/svg/text_mobject.py@@ -5,7 +5,7 @@ import hashlibimport cairofrom ...constants import *-from ...config import config,file_writer_config+from ...config import config, file_writer_configfrom ...container.container import Containerfrom ...logger import loggerfrom ...mobject.geometry import Dot, Rectangle@@ -30,34 +30,34 @@ class TextSetting(object):class Text(SVGMobject):CONFIG = {# Mobject- 'color': WHITE,- 'height': None,- 'width': None,- 'fill_opacity': 1,- 'stroke_width': 0,+ "color": WHITE,+ "height": None,+ "width": None,+ "fill_opacity": 1,+ "stroke_width": 0,"should_center": True,"unpack_groups": True,# Text- 'font': '',- 'gradient': None,- 'lsh': -1,- 'size': 1,- 'slant': NORMAL,- 'weight': NORMAL,- 't2c': {},- 't2f': {},- 't2g': {},- 't2s': {},- 't2w': {},- 'tab_width': 4,+ "font": "",+ "gradient": None,+ "lsh": -1,+ "size": 1,+ "slant": NORMAL,+ "weight": NORMAL,+ "t2c": {},+ "t2f": {},+ "t2g": {},+ "t2s": {},+ "t2w": {},+ "tab_width": 4,}def __init__(self, text, **config):self.full2short(config)digest_config(self, config)text_without_tabs = text- if text.find('\t') != -1:- text_without_tabs = text.replace('\t', ' '*self.tab_width)+ if text.find("\t") != -1:+ text_without_tabs = text.replace("\t", " " * self.tab_width)self.text = text_without_tabsself.lsh = self.size if self.lsh == -1 else self.lsh@@ -77,7 +77,11 @@ class Text(SVGMobject):each.clear_points()for index, point in enumerate(points):each.append_points([point])- if index != len(points) - 1 and (index + 1) % nppc == 0 and any(point != points[index+1]):+ if (+ index != len(points) - 1+ and (index + 1) % nppc == 0+ and any(point != points[index + 1])+ ):each.add_line_to(last)last = points[index + 1]each.add_line_to(last)@@ -96,22 +100,27 @@ class Text(SVGMobject):def get_space_width(self):size = self.size * 10- dir_name = file_writer_config['text_dir']- file_name = os.path.join(dir_name, "space") + '.svg'+ dir_name = file_writer_config["text_dir"]+ file_name = os.path.join(dir_name, "space") + ".svg"surface = cairo.SVGSurface(file_name, 600, 400)context = cairo.Context(surface)context.set_font_size(size)context.move_to(START_X, START_Y)- context.select_font_face(self.font, self.str2slant(self.slant), self.str2weight(self.weight))+ context.select_font_face(+ self.font, self.str2slant(self.slant), self.str2weight(self.weight)+ )context.move_to(START_X, START_Y)context.show_text("_")surface.finish()- svg_with_space = SVGMobject(file_name, height=self.height,- width=self.width,- stroke_width=self.stroke_width,- should_center=self.should_center,- unpack_groups=self.unpack_groups, )+ svg_with_space = SVGMobject(+ file_name,+ height=self.height,+ width=self.width,+ stroke_width=self.stroke_width,+ should_center=self.should_center,+ unpack_groups=self.unpack_groups,+ )space_width = svg_with_space.get_width()return space_width@@ -128,9 +137,13 @@ class Text(SVGMobject):breakfirst_visible_char_index = iif first_visible_char_index != 0:- space = Rectangle(width=space_width * front_spaces_count, height=max_height, fill_opacity=0,- stroke_opacity=0,- stroke_width=0)+ space = Rectangle(+ width=space_width * front_spaces_count,+ height=max_height,+ fill_opacity=0,+ stroke_opacity=0,+ stroke_width=0,+ )text_width = self.get_width()space.move_to(np.array([-text_width / 2, max_height / 2, 0]))self.next_to(space, direction=RIGHT, buff=0)@@ -146,36 +159,44 @@ class Text(SVGMobject):breaklast_visible_char_index = iif last_visible_char_index != self.text.__len__() - 1:- space = Rectangle(width=space_width * last_spaces_count, height=max_height, fill_opacity=0,- stroke_opacity=0,- stroke_width=0)+ space = Rectangle(+ width=space_width * last_spaces_count,+ height=max_height,+ fill_opacity=0,+ stroke_opacity=0,+ stroke_width=0,+ )text_width = self.get_width()space.move_to(np.array([-text_width / 2, max_height / 2, 0]))self.next_to(space, direction=LEFT, buff=0)self.submobjects.append(space)- self.move_to(np.array([0,0,0]))+ self.move_to(np.array([0, 0, 0]))def apply_space_chars(self):char_index = 0while char_index < self.text.__len__() - 1:char_index += 1- if self.text[char_index] == " " or self.text[char_index] == "\t" or self.text[char_index] == "\n":+ if (+ self.text[char_index] == " "+ or self.text[char_index] == "\t"+ or self.text[char_index] == "\n"+ ):space = Dot(fill_opacity=0, stroke_opacity=0)space.move_to(self.submobjects[char_index - 1].get_center())self.submobjects.insert(char_index, space)def remove_last_M(self, file_name):- with open(file_name, 'r') as fpr:+ with open(file_name, "r") as fpr:content = fpr.read()content = re.sub(r'Z M [^A-Za-z]*? "\/>', 'Z "/>', content)- with open(file_name, 'w') as fpw:+ with open(file_name, "w") as fpw:fpw.write(content)def find_indexes(self, word):- m = re.match(r'\[([0-9\-]{0,}):([0-9\-]{0,})\]', word)+ m = re.match(r"\[([0-9\-]{0,}):([0-9\-]{0,})\]", word)if m:- start = int(m.group(1)) if m.group(1) != '' else 0- end = int(m.group(2)) if m.group(2) != '' else len(self.text)+ start = int(m.group(1)) if m.group(1) != "" else 0+ end = int(m.group(2)) if m.group(2) != "" else len(self.text)start = len(self.text) + start if start < 0 else startend = len(self.text) + end if end < 0 else endreturn [(start, end)]@@ -189,18 +210,18 @@ class Text(SVGMobject):def full2short(self, config):for kwargs in [config, self.CONFIG]:- if kwargs.__contains__('line_spacing_height'):- kwargs['lsh'] = kwargs.pop('line_spacing_height')- if kwargs.__contains__('text2color'):- kwargs['t2c'] = kwargs.pop('text2color')- if kwargs.__contains__('text2font'):- kwargs['t2f'] = kwargs.pop('text2font')- if kwargs.__contains__('text2gradient'):- kwargs['t2g'] = kwargs.pop('text2gradient')- if kwargs.__contains__('text2slant'):- kwargs['t2s'] = kwargs.pop('text2slant')- if kwargs.__contains__('text2weight'):- kwargs['t2w'] = kwargs.pop('text2weight')+ if kwargs.__contains__("line_spacing_height"):+ kwargs["lsh"] = kwargs.pop("line_spacing_height")+ if kwargs.__contains__("text2color"):+ kwargs["t2c"] = kwargs.pop("text2color")+ if kwargs.__contains__("text2font"):+ kwargs["t2f"] = kwargs.pop("text2font")+ if kwargs.__contains__("text2gradient"):+ kwargs["t2g"] = kwargs.pop("text2gradient")+ if kwargs.__contains__("text2slant"):+ kwargs["t2s"] = kwargs.pop("text2slant")+ if kwargs.__contains__("text2weight"):+ kwargs["t2w"] = kwargs.pop("text2weight")def set_color_by_t2c(self, t2c=None):t2c = t2c if t2c else self.t2c@@ -232,7 +253,7 @@ class Text(SVGMobject):settings = self.font + self.slant + self.weightsettings += str(self.t2f) + str(self.t2s) + str(self.t2w)settings += str(self.lsh) + str(self.size)- id_str = self.text+settings+ id_str = self.text + settingshasher = hashlib.sha256()hasher.update(id_str.encode())return hasher.hexdigest()[:16]@@ -261,9 +282,9 @@ class Text(SVGMobject):temp_settings.append(TextSetting(start, len(self.text), *fsw))settings = sorted(temp_settings, key=lambda setting: setting.start)- if re.search(r'\n', self.text):+ if re.search(r"\n", self.text):line_num = 0- for start, end in self.find_indexes('\n'):+ for start, end in self.find_indexes("\n"):for setting in settings:if setting.line_num == -1:setting.line_num = line_num@@ -288,12 +309,13 @@ class Text(SVGMobject):size = self.size * 10lsh = self.lsh * 10- if self.font == '':- if NOT_SETTING_FONT_MSG != '':+ if self.font == "":+ if NOT_SETTING_FONT_MSG != "":logger.warning(NOT_SETTING_FONT_MSG)- dir_name = file_writer_config['text_dir']++ dir_name = file_writer_config["text_dir"]hash_name = self.text2hash()- file_name = os.path.join(dir_name, hash_name)+'.svg'+ file_name = os.path.join(dir_name, hash_name) + ".svg"if os.path.exists(file_name):return file_name@@ -309,27 +331,29 @@ class Text(SVGMobject):font = setting.fontslant = self.str2slant(setting.slant)weight = self.str2weight(setting.weight)- text = self.text[setting.start:setting.end].replace('\n', ' ')+ text = self.text[setting.start : setting.end].replace("\n", " ")context.select_font_face(font, slant, weight)if setting.line_num != last_line_num:offset_x = 0last_line_num = setting.line_num- context.move_to(START_X + offset_x, START_Y + lsh*setting.line_num)+ context.move_to(START_X + offset_x, START_Y + lsh * setting.line_num)context.show_text(text)offset_x += context.text_extents(text)[4]return file_name+class TextWithFixHeight(Text):def __init__(self, text, **kwargs):Text.__init__(self, text, **kwargs)max_height = Text("(gyt{[/QW", **kwargs).get_height()- rectangle = Rectangle(width=0, height=max_height, fill_opacity=0,- stroke_opacity=0,- stroke_width=0)+ rectangle = Rectangle(+ width=0, height=max_height, fill_opacity=0, stroke_opacity=0, stroke_width=0+ )self.submobjects.append(rectangle)+class Paragraph(VGroup):CONFIG = {"line_spacing": 0.1,@@ -343,7 +367,9 @@ class Paragraph(VGroup):self.lines.append([])for line_no in range(self.lines_list.__len__()):if "\n" in self.lines_list[line_no]:- self.lines_list[line_no:line_no + 1] = self.lines_list[line_no].split("\n")+ self.lines_list[line_no : line_no + 1] = self.lines_list[line_no].split(+ "\n"+ )for line_no in range(self.lines_list.__len__()):self.lines[0].append(TextWithFixHeight(self.lines_list[line_no], **config))self.char_height = TextWithFixHeight("(", **config).get_height()@@ -351,7 +377,9 @@ class Paragraph(VGroup):self.lines[1].extend([self.alignment for _ in range(self.lines_list.__len__())])self.lines[0][0].move_to(np.array([0, 0, 0]))self.align_lines()- VGroup.__init__(self, *[self.lines[0][i] for i in range(self.lines[0].__len__())], **config)+ VGroup.__init__(+ self, *[self.lines[0][i] for i in range(self.lines[0].__len__())], **config+ )self.move_to(np.array([0, 0, 0]))def set_all_lines_alignment(self, alignment):@@ -367,34 +395,64 @@ class Paragraph(VGroup):def change_alignment_for_a_line(self, alignment, line_no):self.lines[1][line_no] = alignmentif self.lines[1][line_no] == "center":- self[line_no].move_to(self.get_top() +- np.array([0, -self.char_height / 2, 0]) +- np.array([0, - line_no * (self.char_height + self.line_spacing), 0]))+ self[line_no].move_to(+ self.get_top()+ + np.array([0, -self.char_height / 2, 0])+ + np.array([0, -line_no * (self.char_height + self.line_spacing), 0])+ )elif self.lines[1][line_no] == "right":- self[line_no].move_to(self.get_top() +- np.array([0, -self.char_height / 2, 0]) +- np.array([self.get_width() / 2 - self.lines[0][line_no].get_width() / 2,- - line_no * (self.char_height + self.line_spacing), 0])- )+ self[line_no].move_to(+ self.get_top()+ + np.array([0, -self.char_height / 2, 0])+ + np.array(+ [+ self.get_width() / 2 - self.lines[0][line_no].get_width() / 2,+ -line_no * (self.char_height + self.line_spacing),+ 0,+ ]+ )+ )elif self.lines[1][line_no] == "left":- self[line_no].move_to(self.get_top() +- np.array([0, -self.char_height / 2, 0]) +- np.array([- self.get_width() / 2 + self.lines[0][line_no].get_width() / 2,- - line_no * (self.char_height + self.line_spacing), 0])- )+ self[line_no].move_to(+ self.get_top()+ + np.array([0, -self.char_height / 2, 0])+ + np.array(+ [+ -self.get_width() / 2 + self.lines[0][line_no].get_width() / 2,+ -line_no * (self.char_height + self.line_spacing),+ 0,+ ]+ )+ )def align_lines(self):for line_no in range(0, self.lines[0].__len__()):if self.lines[1][line_no] == "center":self.lines[0][line_no].move_to(- np.array([0, 0, 0]) + np.array([0, - line_no * (self.char_height + self.line_spacing), 0]))+ np.array([0, 0, 0])+ + np.array(+ [0, -line_no * (self.char_height + self.line_spacing), 0]+ )+ )elif self.lines[1][line_no] == "left":- self.lines[0][line_no].move_to(np.array([0, 0, 0]) +- np.array([self.lines[0][line_no].get_width() / 2,- - line_no * (self.char_height + self.line_spacing), 0])- )+ self.lines[0][line_no].move_to(+ np.array([0, 0, 0])+ + np.array(+ [+ self.lines[0][line_no].get_width() / 2,+ -line_no * (self.char_height + self.line_spacing),+ 0,+ ]+ )+ )elif self.lines[1][line_no] == "right":- self.lines[0][line_no].move_to(np.array([0, 0, 0]) +- np.array([- self.lines[0][line_no].get_width() / 2,- - line_no * (self.char_height + self.line_spacing), 0])- )+ self.lines[0][line_no].move_to(+ np.array([0, 0, 0])+ + np.array(+ [+ -self.lines[0][line_no].get_width() / 2,+ -line_no * (self.char_height + self.line_spacing),+ 0,+ ]+ )+ )diff --git a/manim/mobject/three_d_shading_utils.py b/manim/mobject/three_d_shading_utils.pyindex 8ed287735..89526e609 100644--- a/manim/mobject/three_d_shading_utils.py+++ b/manim/mobject/three_d_shading_utils.py@@ -39,18 +39,13 @@ def get_3d_vmob_unit_normal(vmob, point_index):im1 = i - 1 if i > 0 else (n_points - 2)ip1 = i + 1 if i < (n_points - 1) else 1return get_unit_normal(- vmob.points[ip1] - vmob.points[i],- vmob.points[im1] - vmob.points[i],+ vmob.points[ip1] - vmob.points[i], vmob.points[im1] - vmob.points[i],)def get_3d_vmob_start_corner_unit_normal(vmob):- return get_3d_vmob_unit_normal(- vmob, get_3d_vmob_start_corner_index(vmob)- )+ return get_3d_vmob_unit_normal(vmob, get_3d_vmob_start_corner_index(vmob))def get_3d_vmob_end_corner_unit_normal(vmob):- return get_3d_vmob_unit_normal(- vmob, get_3d_vmob_end_corner_index(vmob)- )\ No newline at end of file+ return get_3d_vmob_unit_normal(vmob, get_3d_vmob_end_corner_index(vmob))diff --git a/manim/mobject/three_d_utils.py b/manim/mobject/three_d_utils.pyindex 60c6a7231..bf02d3321 100644--- a/manim/mobject/three_d_utils.py+++ b/manim/mobject/three_d_utils.py@@ -41,8 +41,7 @@ def get_3d_vmob_unit_normal(vmob, point_index):im3 = i - 3 if i > 2 else (n_points - 4)ip3 = i + 3 if i < (n_points - 3) else 3unit_normal = get_unit_normal(- vmob.points[ip3] - vmob.points[i],- vmob.points[im3] - vmob.points[i],+ vmob.points[ip3] - vmob.points[i], vmob.points[im3] - vmob.points[i],)if get_norm(unit_normal) == 0:return np.array(UP)@@ -50,12 +49,8 @@ def get_3d_vmob_unit_normal(vmob, point_index):def get_3d_vmob_start_corner_unit_normal(vmob):- return get_3d_vmob_unit_normal(- vmob, get_3d_vmob_start_corner_index(vmob)- )+ return get_3d_vmob_unit_normal(vmob, get_3d_vmob_start_corner_index(vmob))def get_3d_vmob_end_corner_unit_normal(vmob):- return get_3d_vmob_unit_normal(- vmob, get_3d_vmob_end_corner_index(vmob)- )\ No newline at end of file+ return get_3d_vmob_unit_normal(vmob, get_3d_vmob_end_corner_index(vmob))diff --git a/manim/mobject/three_dimensions.py b/manim/mobject/three_dimensions.pyindex eba3d08b4..4f1194dd4 100644--- a/manim/mobject/three_dimensions.py+++ b/manim/mobject/three_dimensions.py@@ -60,16 +60,12 @@ class ParametricSurface(VGroup):faces = VGroup()for i in range(len(u_values) - 1):for j in range(len(v_values) - 1):- u1, u2 = u_values[i:i + 2]- v1, v2 = v_values[j:j + 2]+ u1, u2 = u_values[i : i + 2]+ v1, v2 = v_values[j : j + 2]face = ThreeDVMobject()- face.set_points_as_corners([- [u1, v1, 0],- [u2, v1, 0],- [u2, v2, 0],- [u1, v2, 0],- [u1, v1, 0],- ])+ face.set_points_as_corners(+ [[u1, v1, 0], [u2, v1, 0], [u2, v2, 0], [u1, v2, 0], [u1, v1, 0],]+ )faces.add(face)face.u_index = iface.v_index = j@@ -77,10 +73,7 @@ class ParametricSurface(VGroup):face.u2 = u2face.v1 = v1face.v2 = v2- faces.set_fill(- color=self.fill_color,- opacity=self.fill_opacity- )+ faces.set_fill(color=self.fill_color, opacity=self.fill_opacity)faces.set_stroke(color=self.stroke_color,width=self.stroke_width,@@ -111,17 +104,11 @@ class Sphere(ParametricSurface):}def __init__(self, **kwargs):- ParametricSurface.__init__(- self, self.func, **kwargs- )+ ParametricSurface.__init__(self, self.func, **kwargs)self.scale(self.radius)def func(self, u, v):- return np.array([- np.cos(v) * np.sin(u),- np.sin(v) * np.sin(u),- np.cos(u)- ])+ return np.array([np.cos(v) * np.sin(u), np.sin(v) * np.sin(u), np.cos(u)])class Cube(VGroup):@@ -134,10 +121,7 @@ class Cube(VGroup):def generate_points(self):for vect in IN, OUT, LEFT, RIGHT, UP, DOWN:- face = Square(- side_length=self.side_length,- shade_in_3d=True,- )+ face = Square(side_length=self.side_length, shade_in_3d=True,)face.flip()face.shift(self.side_length * OUT / 2.0)face.apply_matrix(z_to_vector(vect))@@ -146,11 +130,9 @@ class Cube(VGroup):class Prism(Cube):- CONFIG = {- "dimensions": [3, 2, 1]- }+ CONFIG = {"dimensions": [3, 2, 1]}def generate_points(self):Cube.generate_points(self)for dim, value in enumerate(self.dimensions):- self.rescale_to_fit(value, dim, stretch=True)\ No newline at end of file+ self.rescale_to_fit(value, dim, stretch=True)diff --git a/manim/mobject/types/image_mobject.py b/manim/mobject/types/image_mobject.pyindex 9a25b2f15..1909f3489 100644--- a/manim/mobject/types/image_mobject.py+++ b/manim/mobject/types/image_mobject.py@@ -15,6 +15,7 @@ class AbstractImageMobject(Mobject):"""Automatically filters out black pixels"""+CONFIG = {"height": 2.0,"pixel_array_dtype": "uint8",@@ -29,11 +30,7 @@ class AbstractImageMobject(Mobject):def reset_points(self):# Corresponding corners of image are fixed to these 3 points- self.points = np.array([- UP + LEFT,- UP + RIGHT,- DOWN + LEFT,- ])+ self.points = np.array([UP + LEFT, UP + RIGHT, DOWN + LEFT,])self.center()h, w = self.get_pixel_array().shape[:2]self.stretch_to_fit_height(self.height)@@ -70,8 +67,7 @@ class ImageMobject(AbstractImageMobject):pa = pa.repeat(3, axis=2)if pa.shape[2] == 3:alphas = 255 * np.ones(- list(pa.shape[:2]) + [1],- dtype=self.pixel_array_dtype+ list(pa.shape[:2]) + [1], dtype=self.pixel_array_dtype)pa = np.append(pa, alphas, axis=2)self.pixel_array = pa@@ -99,11 +95,12 @@ class ImageMobject(AbstractImageMobject):return selfdef interpolate_color(self, mobject1, mobject2, alpha):- assert(mobject1.pixel_array.shape == mobject2.pixel_array.shape)+ assert mobject1.pixel_array.shape == mobject2.pixel_array.shapeself.pixel_array = interpolate(mobject1.pixel_array, mobject2.pixel_array, alpha).astype(self.pixel_array_dtype)+# TODO, add the ability to have the dimensions/orientation of this# mobject more strongly tied to the frame of the camera it contains,# in the case where that's a MovingCamera@@ -130,4 +127,4 @@ class ImageMobjectFromCamera(AbstractImageMobject):config.update(kwargs)self.display_frame = SurroundingRectangle(self, **config)self.add(self.display_frame)- return self\ No newline at end of file+ return selfdiff --git a/manim/mobject/types/point_cloud_mobject.py b/manim/mobject/types/point_cloud_mobject.pyindex da8860cc1..c0bd8a199 100644--- a/manim/mobject/types/point_cloud_mobject.py+++ b/manim/mobject/types/point_cloud_mobject.py@@ -32,11 +32,7 @@ class PMobject(Mobject):self.points = np.append(self.points, points, axis=0)if rgbas is None:color = Color(color) if color else self.color- rgbas = np.repeat(- [color_to_rgba(color, alpha)],- num_new_points,- axis=0- )+ rgbas = np.repeat([color_to_rgba(color, alpha)], num_new_points, axis=0)elif len(rgbas) != len(points):raise Exception("points and rgbas must have same shape")self.rgbas = np.append(self.rgbas, rgbas, axis=0)@@ -61,22 +57,25 @@ class PMobject(Mobject):# def set_color_by_gradient(self, start_color, end_color):def set_color_by_gradient(self, *colors):- self.rgbas = np.array(list(map(- color_to_rgba,- color_gradient(colors, len(self.points))- )))+ self.rgbas = np.array(+ list(map(color_to_rgba, color_gradient(colors, len(self.points))))+ )return selfstart_rgba, end_rgba = list(map(color_to_rgba, [start_color, end_color]))for mob in self.family_members_with_points():num_points = mob.get_num_points()- mob.rgbas = np.array([- interpolate(start_rgba, end_rgba, alpha)- for alpha in np.arange(num_points) / float(num_points)- ])+ mob.rgbas = np.array(+ [+ interpolate(start_rgba, end_rgba, alpha)+ for alpha in np.arange(num_points) / float(num_points)+ ]+ )return self- def set_colors_by_radial_gradient(self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK):+ def set_colors_by_radial_gradient(+ self, center=None, radius=1, inner_color=WHITE, outer_color=BLACK+ ):start_rgba, end_rgba = list(map(color_to_rgba, [start_color, end_color]))if center is None:center = self.get_center()@@ -84,9 +83,7 @@ class PMobject(Mobject):num_points = mob.get_num_points()t = min(1, np.abs(mob.get_center() - center) / radius)- mob.rgbas = np.array(- [interpolate(start_rgba, end_rgba, t)] * num_points- )+ mob.rgbas = np.array([interpolate(start_rgba, end_rgba, t)] * num_points)return selfdef match_colors(self, mobject):@@ -108,9 +105,7 @@ class PMobject(Mobject):for mob in self.family_members_with_points():num_points = self.get_num_points()mob.apply_over_attr_arrays(- lambda arr: arr[- np.arange(0, num_points, factor)- ]+ lambda arr: arr[np.arange(0, num_points, factor)])return self@@ -119,9 +114,7 @@ class PMobject(Mobject):function is any map from R^3 to R"""for mob in self.family_members_with_points():- indices = np.argsort(- np.apply_along_axis(function, 1, mob.points)- )+ indices = np.argsort(np.apply_along_axis(function, 1, mob.points))mob.apply_over_attr_arrays(lambda arr: arr[indices])return self@@ -151,11 +144,9 @@ class PMobject(Mobject):# Alignmentdef align_points_with_larger(self, larger_mobject):- assert(isinstance(larger_mobject, PMobject))+ assert isinstance(larger_mobject, PMobject)self.apply_over_attr_arrays(- lambda a: stretch_array_to_length(- a, larger_mobject.get_num_points()- )+ lambda a: stretch_array_to_length(a, larger_mobject.get_num_points()))def get_point_mobject(self, center=None):@@ -164,21 +155,16 @@ class PMobject(Mobject):return Point(center)def interpolate_color(self, mobject1, mobject2, alpha):- self.rgbas = interpolate(- mobject1.rgbas, mobject2.rgbas, alpha+ self.rgbas = interpolate(mobject1.rgbas, mobject2.rgbas, alpha)+ self.set_stroke_width(+ interpolate(+ mobject1.get_stroke_width(), mobject2.get_stroke_width(), alpha,+ ))- self.set_stroke_width(interpolate(- mobject1.get_stroke_width(),- mobject2.get_stroke_width(),- alpha,- ))return selfdef pointwise_become_partial(self, mobject, a, b):- lower_index, upper_index = [- int(x * mobject.get_num_points())- for x in (a, b)- ]+ lower_index, upper_index = [int(x * mobject.get_num_points()) for x in (a, b)]for attr in self.get_array_attrs():full_array = getattr(mobject, attr)partial_array = full_array[lower_index:upper_index]@@ -203,10 +189,7 @@ class Mobject1D(PMobject):points = [start]else:epsilon = self.epsilon / length- points = [- interpolate(start, end, t)- for t in np.arange(0, 1, epsilon)- ]+ points = [interpolate(start, end, t) for t in np.arange(0, 1, epsilon)]self.add_points(points, color=color)@@ -242,11 +225,13 @@ class PointCloudDot(Mobject1D):self.shift(center)def generate_points(self):- self.add_points([- r * (np.cos(theta) * RIGHT + np.sin(theta) * UP)- for r in np.arange(0, self.radius, self.epsilon)- for theta in np.arange(0, 2 * np.pi, self.epsilon / r)- ])+ self.add_points(+ [+ r * (np.cos(theta) * RIGHT + np.sin(theta) * UP)+ for r in np.arange(0, self.radius, self.epsilon)+ for theta in np.arange(0, 2 * np.pi, self.epsilon / r)+ ]+ )class Point(PMobject):@@ -256,4 +241,4 @@ class Point(PMobject):def __init__(self, location=ORIGIN, **kwargs):PMobject.__init__(self, **kwargs)- self.add_points([location])\ No newline at end of file+ self.add_points([location])diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.pyindex 66cfec733..805c23000 100644--- a/manim/mobject/types/vectorized_mobject.py+++ b/manim/mobject/types/vectorized_mobject.py@@ -67,8 +67,7 @@ class VMobject(Mobject):# Colorsdef init_colors(self):self.set_fill(- color=self.fill_color or self.color,- opacity=self.fill_opacity,+ color=self.fill_color or self.color, opacity=self.fill_opacity,)self.set_stroke(color=self.stroke_color or self.color,@@ -81,8 +80,7 @@ class VMobject(Mobject):opacity=self.background_stroke_opacity,)self.set_sheen(- factor=self.sheen_factor,- direction=self.sheen_direction,+ factor=self.sheen_factor, direction=self.sheen_direction,)return self@@ -96,10 +94,9 @@ class VMobject(Mobject):"""colors = list(tuplify(color))opacities = list(tuplify(opacity))- rgbas = np.array([- color_to_rgba(c, o)- for c, o in zip(*make_even(colors, opacities))- ])+ rgbas = np.array(+ [color_to_rgba(c, o) for c, o in zip(*make_even(colors, opacities))]+ )sheen_factor = self.get_sheen_factor()if sheen_factor != 0 and len(rgbas) == 1:@@ -120,9 +117,7 @@ class VMobject(Mobject):# one. 99% of the time they'll be the same.curr_rgbas = getattr(self, array_name)if len(curr_rgbas) < len(rgbas):- curr_rgbas = stretch_array_to_length(- curr_rgbas, len(rgbas)- )+ curr_rgbas = stretch_array_to_length(curr_rgbas, len(rgbas))setattr(self, array_name, curr_rgbas)elif len(rgbas) < len(curr_rgbas):rgbas = stretch_array_to_length(rgbas, len(curr_rgbas))@@ -141,13 +136,12 @@ class VMobject(Mobject):self.update_rgbas_array("fill_rgbas", color, opacity)return self- def set_stroke(self, color=None, width=None, opacity=None,- background=False, family=True):+ def set_stroke(+ self, color=None, width=None, opacity=None, background=False, family=True+ ):if family:for submobject in self.submobjects:- submobject.set_stroke(- color, width, opacity, background, family- )+ submobject.set_stroke(color, width, opacity, background, family)if background:array_name = "background_stroke_rgbas"width_name = "background_stroke_width"@@ -164,24 +158,22 @@ class VMobject(Mobject):self.set_stroke(**kwargs)return self- def set_style(self,- fill_color=None,- fill_opacity=None,- stroke_color=None,- stroke_width=None,- stroke_opacity=None,- background_stroke_color=None,- background_stroke_width=None,- background_stroke_opacity=None,- sheen_factor=None,- sheen_direction=None,- background_image_file=None,- family=True):- self.set_fill(- color=fill_color,- opacity=fill_opacity,- family=family- )+ def set_style(+ self,+ fill_color=None,+ fill_opacity=None,+ stroke_color=None,+ stroke_width=None,+ stroke_opacity=None,+ background_stroke_color=None,+ background_stroke_width=None,+ background_stroke_opacity=None,+ sheen_factor=None,+ sheen_direction=None,+ background_image_file=None,+ family=True,+ ):+ self.set_fill(color=fill_color, opacity=fill_opacity, family=family)self.set_stroke(color=stroke_color,width=stroke_width,@@ -196,9 +188,7 @@ class VMobject(Mobject):)if sheen_factor:self.set_sheen(- factor=sheen_factor,- direction=sheen_direction,- family=family,+ factor=sheen_factor, direction=sheen_direction, family=family,)if background_image_file:self.color_using_background_image(background_image_file)@@ -248,18 +238,13 @@ class VMobject(Mobject):def fade(self, darkness=0.5, family=True):factor = 1.0 - darknessself.set_fill(- opacity=factor * self.get_fill_opacity(),- family=False,+ opacity=factor * self.get_fill_opacity(), family=False,)self.set_stroke(- opacity=factor * self.get_stroke_opacity(),- family=False,+ opacity=factor * self.get_stroke_opacity(), family=False,)self.set_background_stroke(- opacity=factor * self.get_stroke_opacity(- background=True- ),- family=False,+ opacity=factor * self.get_stroke_opacity(background=True), family=False,)super().fade(darkness, family)return self@@ -285,10 +270,7 @@ class VMobject(Mobject):return self.get_fill_opacities()[0]def get_fill_colors(self):- return [- Color(rgb=rgba[:3])- for rgba in self.get_fill_rgbas()- ]+ return [Color(rgb=rgba[:3]) for rgba in self.get_fill_rgbas()]def get_fill_opacities(self):return self.get_fill_rgbas()[:, 3]@@ -317,10 +299,7 @@ class VMobject(Mobject):return self.get_stroke_opacities(background)[0]def get_stroke_colors(self, background=False):- return [- Color(rgb=rgba[:3])- for rgba in self.get_stroke_rgbas(background)- ]+ return [Color(rgb=rgba[:3]) for rgba in self.get_stroke_rgbas(background)]def get_stroke_opacities(self, background=False):return self.get_stroke_rgbas(background)[:, 3]@@ -366,10 +345,9 @@ class VMobject(Mobject):else:direction = self.get_sheen_direction()c = self.get_center()- bases = np.array([- self.get_edge_center(vect) - c- for vect in [RIGHT, UP, OUT]- ]).transpose()+ bases = np.array(+ [self.get_edge_center(vect) - c for vect in [RIGHT, UP, OUT]]+ ).transpose()offset = np.dot(bases, direction)return (c - offset, c + offset)@@ -403,7 +381,7 @@ class VMobject(Mobject):return np.array(self.points)def set_anchors_and_handles(self, anchors1, handles1, handles2, anchors2):- assert(len(anchors1) == len(handles1) == len(handles2) == len(anchors2))+ assert len(anchors1) == len(handles1) == len(handles2) == len(anchors2)nppcc = self.n_points_per_cubic_curve # 4total_len = nppcc * len(anchors1)self.points = np.zeros((total_len, self.dim))@@ -444,10 +422,12 @@ class VMobject(Mobject):def add_line_to(self, point):nppcc = self.n_points_per_cubic_curve- self.add_cubic_bezier_curve_to(*[- interpolate(self.get_last_point(), point, a)- for a in np.linspace(0, 1, nppcc)[1:]- ])+ self.add_cubic_bezier_curve_to(+ *[+ interpolate(self.get_last_point(), point, a)+ for a in np.linspace(0, 1, nppcc)[1:]+ ]+ )return selfdef add_smooth_curve_to(self, *points):@@ -469,17 +449,13 @@ class VMobject(Mobject):else:self.throw_error_if_no_points()last_h2, last_a2 = self.points[-2:]- last_tangent = (last_a2 - last_h2)+ last_tangent = last_a2 - last_h2handle1 = last_a2 + last_tangentif handle2 is None:to_anchor_vect = new_anchor - last_a2- new_tangent = rotate_vector(- last_tangent, PI, axis=to_anchor_vect- )+ new_tangent = rotate_vector(last_tangent, PI, axis=to_anchor_vect)handle2 = new_anchor - new_tangent- self.append_points([- last_a2, handle1, handle2, new_anchor- ])+ self.append_points([last_a2, handle1, handle2, new_anchor])return selfdef has_new_path_started(self):@@ -490,9 +466,7 @@ class VMobject(Mobject):return self.points[-1]def is_closed(self):- return self.consider_points_equals(- self.points[0], self.points[-1]- )+ return self.consider_points_equals(self.points[0], self.points[-1])def add_points_as_corners(self, points):for point in points:@@ -502,10 +476,9 @@ class VMobject(Mobject):def set_points_as_corners(self, points):nppcc = self.n_points_per_cubic_curvepoints = np.array(points)- self.set_anchors_and_handles(*[- interpolate(points[:-1], points[1:], a)- for a in np.linspace(0, 1, nppcc)- ])+ self.set_anchors_and_handles(+ *[interpolate(points[:-1], points[1:], a) for a in np.linspace(0, 1, nppcc)]+ )return selfdef set_points_smoothly(self, points):@@ -514,17 +487,13 @@ class VMobject(Mobject):return selfdef change_anchor_mode(self, mode):- assert(mode in ["jagged", "smooth"])+ assert mode in ["jagged", "smooth"]nppcc = self.n_points_per_cubic_curvefor submob in self.family_members_with_points():subpaths = submob.get_subpaths()submob.clear_points()for subpath in subpaths:- anchors = np.append(- subpath[::nppcc],- subpath[-1:],- 0- )+ anchors = np.append(subpath[::nppcc], subpath[-1:], 0)if mode == "smooth":h1, h2 = get_smooth_handle_points(anchors)elif mode == "jagged":@@ -545,7 +514,7 @@ class VMobject(Mobject):return self.change_anchor_mode("jagged")def add_subpath(self, points):- assert(len(points) % 4 == 0)+ assert len(points) % 4 == 0self.points = np.append(self.points, points, axis=0)return self@@ -562,7 +531,7 @@ class VMobject(Mobject):factor = self.pre_function_handle_to_anchor_scale_factorself.scale_handle_to_anchor_distances(factor)Mobject.apply_function(self, function)- self.scale_handle_to_anchor_distances(1. / factor)+ self.scale_handle_to_anchor_distances(1.0 / factor)if self.make_smooth_after_applying_functions:self.make_smooth()return self@@ -590,10 +559,7 @@ class VMobject(Mobject):#def consider_points_equals(self, p0, p1):- return np.allclose(- p0, p1,- atol=self.tolerance_for_point_equality- )+ return np.allclose(p0, p1, atol=self.tolerance_for_point_equality)def consider_points_equals_2d(self, p0, p1):"""@@ -602,7 +568,7 @@ class VMobject(Mobject):This uses the algorithm from np.isclose(), but expanded here for the2D point case. NumPy is overkill for such a small question."""- rtol = 1.e-5 # default from np.isclose()+ rtol = 1.0e-5 # default from np.isclose()atol = self.tolerance_for_point_equalityif abs(p0[0] - p1[0]) > atol + rtol * abs(p1[0]):return False@@ -622,16 +588,11 @@ class VMobject(Mobject):"""nppcc = VMobject.CONFIG["n_points_per_cubic_curve"]remainder = len(points) % nppcc- points = points[:len(points) - remainder]- return (- points[i:i + nppcc]- for i in range(0, len(points), nppcc)- )+ points = points[: len(points) - remainder]+ return (points[i : i + nppcc] for i in range(0, len(points), nppcc))def get_cubic_bezier_tuples(self):- return self.get_cubic_bezier_tuples_from_points(- self.get_points()- )+ return self.get_cubic_bezier_tuples_from_points(self.get_points())def _gen_subpaths_from_points(self, points, filter_func):nppcc = self.n_points_per_cubic_curve@@ -647,25 +608,23 @@ class VMobject(Mobject):return list(self._gen_subpaths_from_points(points,- lambda n: not self.consider_points_equals(- points[n - 1], points[n]- ))+ lambda n: not self.consider_points_equals(points[n - 1], points[n]),+ ))def gen_subpaths_from_points_2d(self, points):return self._gen_subpaths_from_points(- points,- lambda n: not self.consider_points_equals_2d(- points[n - 1], points[n]- ))+ points,+ lambda n: not self.consider_points_equals_2d(points[n - 1], points[n]),+ )def get_subpaths(self):return self.get_subpaths_from_points(self.get_points())def get_nth_curve_points(self, n):- assert(n < self.get_num_curves())+ assert n < self.get_num_curves()nppcc = self.n_points_per_cubic_curve- return self.points[nppcc * n:nppcc * (n + 1)]+ return self.points[nppcc * n : nppcc * (n + 1)]def get_nth_curve_function(self, n):return bezier(self.get_nth_curve_points(n))@@ -688,39 +647,31 @@ class VMobject(Mobject):for any i in range(0, len(anchors1))"""nppcc = self.n_points_per_cubic_curve- return [- self.points[i::nppcc]- for i in range(nppcc)- ]+ return [self.points[i::nppcc] for i in range(nppcc)]def get_start_anchors(self):- return self.points[0::self.n_points_per_cubic_curve]+ return self.points[0 :: self.n_points_per_cubic_curve]def get_end_anchors(self):nppcc = self.n_points_per_cubic_curve- return self.points[nppcc - 1::nppcc]+ return self.points[nppcc - 1 :: nppcc]def get_anchors(self):if self.points.shape[0] == 1:return self.points- return np.array(list(it.chain(*zip(- self.get_start_anchors(),- self.get_end_anchors(),- ))))+ return np.array(+ list(it.chain(*zip(self.get_start_anchors(), self.get_end_anchors(),)))+ )def get_points_defining_boundary(self):- return np.array(list(it.chain(*[- sm.get_anchors()- for sm in self.get_family()- ])))+ return np.array(list(it.chain(*[sm.get_anchors() for sm in self.get_family()])))def get_arc_length(self, n_sample_points=None):if n_sample_points is None:n_sample_points = 4 * self.get_num_curves() + 1- points = np.array([- self.point_from_proportion(a)- for a in np.linspace(0, 1, n_sample_points)- ])+ points = np.array(+ [self.point_from_proportion(a) for a in np.linspace(0, 1, n_sample_points)]+ )diffs = points[1:] - points[:-1]norms = np.apply_along_axis(get_norm, 1, diffs)return np.sum(norms)@@ -775,9 +726,7 @@ class VMobject(Mobject):if self.has_new_path_started():new_path_point = self.get_last_point()- new_points = self.insert_n_curves_to_point_list(- n, self.get_points()- )+ new_points = self.insert_n_curves_to_point_list(n, self.get_points())self.set_points(new_points)if new_path_point is not None:@@ -802,10 +751,7 @@ class VMobject(Mobject):# that the nth curve of our path should be split# into k pieces. In the above example, this would# be [2, 1, 2, 1, 2, 1, 2, 1, 2, 1]- split_factors = [- sum(repeat_indices == i)- for i in range(curr_num)- ]+ split_factors = [sum(repeat_indices == i) for i in range(curr_num)]new_points = np.zeros((0, self.dim))for quad, sf in zip(bezier_quads, split_factors):# What was once a single cubic curve defined@@ -814,9 +760,7 @@ class VMobject(Mobject):alphas = np.linspace(0, 1, sf + 1)for a1, a2 in zip(alphas, alphas[1:]):new_points = np.append(- new_points,- partial_bezier_points(quad, a1, a2),- axis=0+ new_points, partial_bezier_points(quad, a1, a2), axis=0)return new_points@@ -851,16 +795,16 @@ class VMobject(Mobject):"sheen_factor",]for attr in attrs:- setattr(self, attr, interpolate(- getattr(mobject1, attr),- getattr(mobject2, attr),- alpha- ))+ setattr(+ self,+ attr,+ interpolate(getattr(mobject1, attr), getattr(mobject2, attr), alpha),+ )if alpha == 1.0:setattr(self, attr, getattr(mobject2, attr))def pointwise_become_partial(self, vmobject, a, b):- assert(isinstance(vmobject, VMobject))+ assert isinstance(vmobject, VMobject)# Partial curve includes three portions:# - A middle section, which matches the curve exactly# - A start, which is some ending portion of an inner cubic@@ -878,19 +822,20 @@ class VMobject(Mobject):if num_cubics == 0:return selfif lower_index == upper_index:- self.append_points(partial_bezier_points(- bezier_quads[lower_index],- lower_residue, upper_residue- ))+ self.append_points(+ partial_bezier_points(+ bezier_quads[lower_index], lower_residue, upper_residue+ )+ )else:- self.append_points(partial_bezier_points(- bezier_quads[lower_index], lower_residue, 1- ))- for quad in bezier_quads[lower_index + 1:upper_index]:+ self.append_points(+ partial_bezier_points(bezier_quads[lower_index], lower_residue, 1)+ )+ for quad in bezier_quads[lower_index + 1 : upper_index]:self.append_points(quad)- self.append_points(partial_bezier_points(- bezier_quads[upper_index], 0, upper_residue- ))+ self.append_points(+ partial_bezier_points(bezier_quads[upper_index], 0, upper_residue)+ )return selfdef get_subcurve(self, a, b):@@ -906,6 +851,7 @@ class VGroup(VMobject):VMobject.__init__(self, **kwargs)self.add(*vmobjects)+class VDict(VMobject):"""A VGroup-like class, also offering submobject access bykey, like a python dict@@ -945,7 +891,6 @@ class VDict(VMobject):self.show_keys = show_keysself.submob_dict = {}self.add(*pairs)-def add(self, *pairs):"""Adds the key-value pairs to the :class:`VDict` object.@@ -974,14 +919,15 @@ class VDict(VMobject):for pair in pairs:key = pair[0]value = pair[1]-+mob = valueif self.show_keys:# This import is here and not at the top to avoid circular importfrom ...mobject.svg.tex_mobject import TextMobject+key_text = TextMobject(str(key)).next_to(value, LEFT)mob.add(key_text)-+self.submob_dict[key] = mobsuper().add(value)return self@@ -1008,7 +954,7 @@ class VDict(VMobject):my_dict.remove('square')"""if key not in self.submob_dict:- raise Exception("The given key '%s' is not present in the VDict" %str(key))+ raise Exception("The given key '%s' is not present in the VDict" % str(key))super().remove(self.submob_dict[key])del self.submob_dict[key]return self@@ -1032,7 +978,7 @@ class VDict(VMobject):self.play(ShowCreation(my_dict['s']))"""submob = self.submob_dict[key]- return submob+ return submobdef __setitem__(self, key, value):"""Overriding the [] operator for assigning submobject like a python dict@@ -1114,11 +1060,7 @@ class CurvesAsSubmobjects(VGroup):class DashedVMobject(VMobject):- CONFIG = {- "num_dashes": 15,- "positive_space_ratio": 0.5,- "color": WHITE- }+ CONFIG = {"num_dashes": 15, "positive_space_ratio": 0.5, "color": WHITE}def __init__(self, vmobject, **kwargs):VMobject.__init__(self, **kwargs)@@ -1129,17 +1071,19 @@ class DashedVMobject(VMobject):alphas = np.linspace(0, 1, num_dashes + 1)# This determines the length of each "dash"- full_d_alpha = (1.0 / num_dashes)+ full_d_alpha = 1.0 / num_dashespartial_d_alpha = full_d_alpha * ps_ratio# Rescale so that the last point of vmobject will# be the end of the last dash- alphas /= (1 - full_d_alpha + partial_d_alpha)+ alphas /= 1 - full_d_alpha + partial_d_alpha- self.add(*[- vmobject.get_subcurve(alpha, alpha + partial_d_alpha)- for alpha in alphas[:-1]- ])+ self.add(+ *[+ vmobject.get_subcurve(alpha, alpha + partial_d_alpha)+ for alpha in alphas[:-1]+ ]+ )# Family is already taken care of by get_subcurve# implementationself.match_style(vmobject, family=False)diff --git a/manim/mobject/value_tracker.py b/manim/mobject/value_tracker.pyindex f832c172e..c08d02925 100644--- a/manim/mobject/value_tracker.py+++ b/manim/mobject/value_tracker.py@@ -27,15 +27,12 @@ class ValueTracker(Mobject):def increment_value(self, d_value):self.set_value(self.get_value() + d_value)- def interpolate(self, mobject1, mobject2,- alpha, path_func=straight_path):+ def interpolate(self, mobject1, mobject2, alpha, path_func=straight_path):"""Turns self into an interpolation between mobject1and mobject2."""- self.points = path_func(- mobject1.points, mobject2.points, alpha- )+ self.points = path_func(mobject1.points, mobject2.points, alpha)return self@@ -60,4 +57,4 @@ class ComplexValueTracker(ValueTracker):def set_value(self, z):z = complex(z)self.points[0, :2] = (z.real, z.imag)- return self\ No newline at end of file+ return selfdiff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.pyindex 0903e54c5..ad5310a72 100644--- a/manim/mobject/vector_field.py+++ b/manim/mobject/vector_field.py@@ -20,20 +20,23 @@ from ..utils.config_ops import digest_configfrom ..utils.rate_functions import linearfrom ..utils.simple_functions import sigmoidfrom ..utils.space_ops import get_norm+# from ..utils.space_ops import normalizeDEFAULT_SCALAR_FIELD_COLORS = [BLUE_E, GREEN, YELLOW, RED]-def get_colored_background_image(scalar_field_func,- number_to_rgb_func,- pixel_height=config['pixel_height'],- pixel_width=config['pixel_width']):- ph = config['pixel_height']- pw = config['pixel_width']- fw = config['frame_width']- fh = config['frame_height']+def get_colored_background_image(+ scalar_field_func,+ number_to_rgb_func,+ pixel_height=config["pixel_height"],+ pixel_width=config["pixel_width"],+):+ ph = config["pixel_height"]+ pw = config["pixel_width"]+ fw = config["frame_width"]+ fh = config["frame_height"]points_array = np.zeros((ph, pw, 3))x_array = np.linspace(-fw / 2, fw / 2, pw)x_array = x_array.reshape((1, len(x_array)))@@ -46,19 +49,16 @@ def get_colored_background_image(scalar_field_func,points_array[:, :, 1] = y_arrayscalars = np.apply_along_axis(scalar_field_func, 2, points_array)rgb_array = number_to_rgb_func(scalars.flatten()).reshape((ph, pw, 3))- return Image.fromarray((rgb_array * 255).astype('uint8'))+ return Image.fromarray((rgb_array * 255).astype("uint8"))-def get_rgb_gradient_function(min_value=0, max_value=1,- colors=[BLUE, RED],- flip_alphas=True, # Why?- ):+def get_rgb_gradient_function(+ min_value=0, max_value=1, colors=[BLUE, RED], flip_alphas=True, # Why?+):rgbs = np.array(list(map(color_to_rgb, colors)))def func(values):- alphas = inverse_interpolate(- min_value, max_value, np.array(values)- )+ alphas = inverse_interpolate(min_value, max_value, np.array(values))alphas = np.clip(alphas, 0, 1)# if flip_alphas:# alphas = 1 - alphas@@ -69,13 +69,13 @@ def get_rgb_gradient_function(min_value=0, max_value=1,inter_alphas = inter_alphas.repeat(3).reshape((len(indices), 3))result = interpolate(rgbs[indices], rgbs[next_indices], inter_alphas)return result+return func-def get_color_field_image_file(scalar_func,- min_value=0, max_value=2,- colors=DEFAULT_SCALAR_FIELD_COLORS- ):+def get_color_field_image_file(+ scalar_func, min_value=0, max_value=2, colors=DEFAULT_SCALAR_FIELD_COLORS+):# try_hashnp.random.seed(0)sample_inputs = 5 * np.random.random(size=(10, 3)) - 10@@ -88,9 +88,7 @@ def get_color_field_image_file(scalar_func,if not os.path.exists(full_path):logger.info("Rendering color field image " + str(func_hash))rgb_gradient_func = get_rgb_gradient_function(- min_value=min_value,- max_value=max_value,- colors=colors+ min_value=min_value, max_value=max_value, colors=colors)image = get_colored_background_image(scalar_func, rgb_gradient_func)image.save(full_path)@@ -98,11 +96,7 @@ def get_color_field_image_file(scalar_func,def move_along_vector_field(mobject, func):- mobject.add_updater(- lambda m, dt: m.shift(- func(m.get_center()) * dt- )- )+ mobject.add_updater(lambda m, dt: m.shift(func(m.get_center()) * dt))return mobject@@ -110,7 +104,7 @@ def move_submobjects_along_vector_field(mobject, func):def apply_nudge(mob, dt):for submob in mob:x, y = submob.get_center()[:2]- if abs(x) < config['frame_width'] and abs(y) < config['frame_height']:+ if abs(x) < config["frame_width"] and abs(y) < config["frame_height"]:submob.shift(func(submob.get_center()) * dt)mobject.add_updater(apply_nudge)@@ -119,23 +113,23 @@ def move_submobjects_along_vector_field(mobject, func):def move_points_along_vector_field(mobject, func):def apply_nudge(self, dt):- self.mobject.apply_function(- lambda p: p + func(p) * dt- )+ self.mobject.apply_function(lambda p: p + func(p) * dt)+mobject.add_updater(apply_nudge)return mobject# Mobjects+class VectorField(VGroup):CONFIG = {"delta_x": 0.5,"delta_y": 0.5,- "x_min": int(np.floor(-config['frame_width'] / 2)),- "x_max": int(np.ceil(config['frame_width'] / 2)),- "y_min": int(np.floor(-config['frame_height'] / 2)),- "y_max": int(np.ceil(config['frame_height'] / 2)),+ "x_min": int(np.floor(-config["frame_width"] / 2)),+ "x_max": int(np.ceil(config["frame_width"] / 2)),+ "y_min": int(np.floor(-config["frame_height"] / 2)),+ "y_max": int(np.ceil(config["frame_height"] / 2)),"min_magnitude": 0,"max_magnitude": 2,"colors": DEFAULT_SCALAR_FIELD_COLORS,@@ -149,21 +143,10 @@ class VectorField(VGroup):VGroup.__init__(self, **kwargs)self.func = funcself.rgb_gradient_function = get_rgb_gradient_function(- self.min_magnitude,- self.max_magnitude,- self.colors,- flip_alphas=False- )- x_range = np.arange(- self.x_min,- self.x_max + self.delta_x,- self.delta_x- )- y_range = np.arange(- self.y_min,- self.y_max + self.delta_y,- self.delta_y+ self.min_magnitude, self.max_magnitude, self.colors, flip_alphas=False)+ x_range = np.arange(self.x_min, self.x_max + self.delta_x, self.delta_x)+ y_range = np.arange(self.y_min, self.y_max + self.delta_y, self.delta_y)for x, y in it.product(x_range, y_range):point = x * RIGHT + y * UPself.add(self.get_vector(point))@@ -180,9 +163,7 @@ class VectorField(VGroup):vector_config.update(kwargs)vect = Vector(output, **vector_config)vect.shift(point)- fill_color = rgb_to_color(- self.rgb_gradient_function(np.array([norm]))[0]- )+ fill_color = rgb_to_color(self.rgb_gradient_function(np.array([norm]))[0])vect.set_color(fill_color)return vect@@ -226,9 +207,7 @@ class StreamLines(VGroup):self.func = funcdt = self.dt- start_points = self.get_start_points(- **self.start_points_generator_config- )+ start_points = self.get_start_points(**self.start_points_generator_config)for point in start_points:points = [point]for t in np.arange(0, self.virtual_time, dt):@@ -245,9 +224,7 @@ class StreamLines(VGroup):if self.color_by_arc_length:len_to_rgb = get_rgb_gradient_function(- self.min_arc_length,- self.max_arc_length,- colors=self.colors,+ self.min_arc_length, self.max_arc_length, colors=self.colors,)for line in self:arc_length = line.get_arc_length()@@ -275,39 +252,40 @@ class StreamLines(VGroup):if noise_factor is None:noise_factor = delta_y / 2- return np.array([- x * RIGHT + y * UP + noise_factor * np.random.random(3)- for n in range(n_repeats)- for x in np.arange(x_min, x_max + delta_x, delta_x)- for y in np.arange(y_min, y_max + delta_y, delta_y)- ])+ return np.array(+ [+ x * RIGHT + y * UP + noise_factor * np.random.random(3)+ for n in range(n_repeats)+ for x in np.arange(x_min, x_max + delta_x, delta_x)+ for y in np.arange(y_min, y_max + delta_y, delta_y)+ ]+ )# TODO: Make it so that you can have a group of stream_lines# varying in response to a changing vector field, and still# animate the resulting flowclass ShowPassingFlashWithThinningStrokeWidth(AnimationGroup):- CONFIG = {- "n_segments": 10,- "time_width": 0.1,- "remover": True- }+ CONFIG = {"n_segments": 10, "time_width": 0.1, "remover": True}def __init__(self, vmobject, **kwargs):digest_config(self, kwargs)max_stroke_width = vmobject.get_stroke_width()max_time_width = kwargs.pop("time_width", self.time_width)- AnimationGroup.__init__(self, *[- ShowPassingFlash(- vmobject.deepcopy().set_stroke(width=stroke_width),- time_width=time_width,- **kwargs- )- for stroke_width, time_width in zip(- np.linspace(0, max_stroke_width, self.n_segments),- np.linspace(max_time_width, 0, self.n_segments)- )- ])+ AnimationGroup.__init__(+ self,+ *[+ ShowPassingFlash(+ vmobject.deepcopy().set_stroke(width=stroke_width),+ time_width=time_width,+ **kwargs,+ )+ for stroke_width, time_width in zip(+ np.linspace(0, max_stroke_width, self.n_segments),+ np.linspace(max_time_width, 0, self.n_segments),+ )+ ],+ )# TODO, this is untested after turning it from a@@ -316,11 +294,7 @@ class AnimatedStreamLines(VGroup):CONFIG = {"lag_range": 4,"line_anim_class": ShowPassingFlash,- "line_anim_config": {- "run_time": 4,- "rate_func": linear,- "time_width": 0.3,- },+ "line_anim_config": {"run_time": 4, "rate_func": linear, "time_width": 0.3,},}def __init__(self, stream_lines, **kwargs):diff --git a/manim/scene/graph_scene.py b/manim/scene/graph_scene.pyindex 23a0b42bc..0b34384e5 100644--- a/manim/scene/graph_scene.py+++ b/manim/scene/graph_scene.py@@ -52,15 +52,15 @@ class GraphScene(Scene):"default_riemann_end_color": GREEN,"area_opacity": 0.8,"num_rects": 50,- "include_tip": False, # add tip at the end of the axes- "x_axis_visibility": True, # show or hide the x axis- "y_axis_visibility": True, # show or hide the y axis- "x_label_position": UP+RIGHT, # where to place the label of the x axis- "y_label_position": UP+RIGHT, # where to place the label of the y axis- "x_add_start": 0, # extend the x axis to the left- "x_add_end": 0, # extend the x axis to the right- "y_add_start": 0, # extend the y axis to the bottom- "y_add_end": 0, # extend the y axis to the top+ "include_tip": False, # add tip at the end of the axes+ "x_axis_visibility": True, # show or hide the x axis+ "y_axis_visibility": True, # show or hide the y axis+ "x_label_position": UP + RIGHT, # where to place the label of the x axis+ "y_label_position": UP + RIGHT, # where to place the label of the y axis+ "x_add_start": 0, # extend the x axis to the left+ "x_add_end": 0, # extend the x axis to the right+ "y_add_start": 0, # extend the y axis to the bottom+ "y_add_end": 0, # extend the y axis to the top}def setup(self):@@ -101,7 +101,7 @@ class GraphScene(Scene):color=self.axes_color,include_tip=self.include_tip,add_start=self.x_add_start,- add_end=self.x_add_end+ add_end=self.x_add_end,)x_axis.shift(self.graph_origin - x_axis.number_to_point(0))if len(self.x_labeled_nums) > 0:@@ -113,7 +113,7 @@ class GraphScene(Scene):x_label.next_to(x_axis.get_tips() if self.include_tip else x_axis.get_tick_marks(),self.x_label_position,- buff=SMALL_BUFF+ buff=SMALL_BUFF,)x_label.shift_onto_screen()x_axis.add(x_label)@@ -138,7 +138,7 @@ class GraphScene(Scene):label_direction=LEFT,include_tip=self.include_tip,add_start=self.y_add_start,- add_end=self.y_add_end+ add_end=self.y_add_end,)y_axis.shift(self.graph_origin - y_axis.number_to_point(0))y_axis.rotate(np.pi / 2, about_point=y_axis.number_to_point(0))@@ -149,8 +149,9 @@ class GraphScene(Scene):if self.y_axis_label:y_label = TextMobject(self.y_axis_label)y_label.next_to(- y_axis.get_corner(self.y_label_position), self.y_label_position,- buff=SMALL_BUFF+ y_axis.get_corner(self.y_label_position),+ self.y_label_position,+ buff=SMALL_BUFF,)y_label.shift_onto_screen()y_axis.add(y_label)@@ -190,7 +191,7 @@ class GraphScene(Scene):np.ndarrayThe array of the coordinates."""- assert(hasattr(self, "x_axis") and hasattr(self, "y_axis"))+ assert hasattr(self, "x_axis") and hasattr(self, "y_axis")result = self.x_axis.number_to_point(x)[0] * RIGHTresult += self.y_axis.number_to_point(y)[1] * UPreturn result@@ -215,16 +216,9 @@ class GraphScene(Scene):tupleThe coordinates on the scene."""- return (self.x_axis.point_to_number(point),- self.y_axis.point_to_number(point))+ return (self.x_axis.point_to_number(point), self.y_axis.point_to_number(point))- def get_graph(- self, func,- color=None,- x_min=None,- x_max=None,- **kwargs- ):+ def get_graph(self, func, color=None, x_min=None, x_max=None, **kwargs):"""This method gets a curve to plot on the graph.@@ -266,11 +260,7 @@ class GraphScene(Scene):y = self.y_maxreturn self.coords_to_point(x, y)- graph = ParametricFunction(- parameterized_function,- color=color,- **kwargs- )+ graph = ParametricFunction(parameterized_function, color=color, **kwargs)graph.underlying_function = funcreturn graph@@ -318,8 +308,9 @@ class GraphScene(Scene):floatThe angle of the tangent with the x axis."""- vect = self.input_to_graph_point(- x + dx, graph) - self.input_to_graph_point(x, graph)+ vect = self.input_to_graph_point(x + dx, graph) - self.input_to_graph_point(+ x, graph+ )return angle_of_vector(vect)def slope_of_tangent(self, *args, **kwargs):@@ -373,6 +364,7 @@ class GraphScene(Scene):def deriv(x):return self.slope_of_tangent(x, graph, dx) / self.space_unit_to_y+return self.get_graph(deriv, **kwargs)def get_graph_label(@@ -422,14 +414,10 @@ class GraphScene(Scene):# Search from right to leftfor x in np.linspace(self.x_max, self.x_min, 100):point = self.input_to_graph_point(x, graph)- if point[1] < config['frame_y_radius']:+ if point[1] < config["frame_y_radius"]:breakx_val = x- label.next_to(- self.input_to_graph_point(x_val, graph),- direction,- buff=buff- )+ label.next_to(self.input_to_graph_point(x_val, graph), direction, buff=buff)label.shift_onto_screen()return label@@ -446,7 +434,7 @@ class GraphScene(Scene):start_color=None,end_color=None,show_signed_area=True,- width_scale_factor=1.001+ width_scale_factor=1.001,):"""This method returns the VGroup() of the Riemann Rectangles for@@ -522,11 +510,18 @@ class GraphScene(Scene):else:raise Exception("Invalid input sample type")graph_point = self.input_to_graph_point(sample_input, graph)- points = VGroup(*list(map(VectorizedPoint, [- self.coords_to_point(x, 0),- self.coords_to_point(x + width_scale_factor * dx, 0),- graph_point- ])))+ points = VGroup(+ *list(+ map(+ VectorizedPoint,+ [+ self.coords_to_point(x, 0),+ self.coords_to_point(x + width_scale_factor * dx, 0),+ graph_point,+ ],+ )+ )+ )rect = Rectangle()rect.replace(points, stretch=True)@@ -540,13 +535,7 @@ class GraphScene(Scene):return rectanglesdef get_riemann_rectangles_list(- self,- graph,- n_iterations,- max_dx=0.5,- power_base=2,- stroke_width=1,- **kwargs+ self, graph, n_iterations, max_dx=0.5, power_base=2, stroke_width=1, **kwargs):"""This method returns a list of multiple VGroups of Riemann@@ -583,9 +572,9 @@ class GraphScene(Scene):return [self.get_riemann_rectangles(graph=graph,- dx=float(max_dx) / (power_base**n),- stroke_width=float(stroke_width) / (power_base**n),- **kwargs+ dx=float(max_dx) / (power_base ** n),+ stroke_width=float(stroke_width) / (power_base ** n),+ **kwargs,)for n in range(n_iterations)]@@ -615,11 +604,7 @@ class GraphScene(Scene):numerator = max(t_max - t_min, 0.0001)dx = float(numerator) / self.num_rectsreturn self.get_riemann_rectangles(- graph,- x_min=t_min,- x_max=t_max,- dx=dx,- stroke_width=0,+ graph, x_min=t_min, x_max=t_max, dx=dx, stroke_width=0,).set_fill(opacity=self.area_opacity)def transform_between_riemann_rects(self, curr_rects, new_rects, **kwargs):@@ -640,10 +625,7 @@ class GraphScene(Scene):added_animsAny other animations to play simultaneously."""- transform_kwargs = {- "run_time": 2,- "lag_ratio": 0.5- }+ transform_kwargs = {"run_time": 2, "lag_ratio": 0.5}added_anims = kwargs.get("added_anims", [])transform_kwargs.update(kwargs)curr_rects.align_submobjects(new_rects)@@ -654,17 +636,9 @@ class GraphScene(Scene):rect.set_fill(opacity=0)else:x_coords.add(x)- self.play(- Transform(curr_rects, new_rects, **transform_kwargs),- *added_anims- )+ self.play(Transform(curr_rects, new_rects, **transform_kwargs), *added_anims)- def get_vertical_line_to_graph(- self,- x, graph,- line_class=Line,- **line_kwargs- ):+ def get_vertical_line_to_graph(self, x, graph, line_class=Line, **line_kwargs):"""This method returns a Vertical line from the x-axis tothe corresponding point on the graph/curve.@@ -695,15 +669,11 @@ class GraphScene(Scene):return line_class(self.coords_to_point(x, 0),self.input_to_graph_point(x, graph),- **line_kwargs+ **line_kwargs,)def get_vertical_lines_to_graph(- self, graph,- x_min=None,- x_max=None,- num_lines=20,- **kwargs+ self, graph, x_min=None, x_max=None, num_lines=20, **kwargs):"""Obtains multiple lines from the x axis to the Graph/curve.@@ -731,14 +701,17 @@ class GraphScene(Scene):"""x_min = x_min or self.x_minx_max = x_max or self.x_max- return VGroup(*[- self.get_vertical_line_to_graph(x, graph, **kwargs)- for x in np.linspace(x_min, x_max, num_lines)- ])+ return VGroup(+ *[+ self.get_vertical_line_to_graph(x, graph, **kwargs)+ for x in np.linspace(x_min, x_max, num_lines)+ ]+ )def get_secant_slope_group(self,- x, graph,+ x,+ graph,dx=None,dx_line_color=None,df_line_color=None,@@ -814,14 +787,8 @@ class GraphScene(Scene):p2 = self.input_to_graph_point(x + dx, graph)interim_point = p2[0] * RIGHT + p1[1] * UP- group.dx_line = Line(- p1, interim_point,- color=dx_line_color- )- group.df_line = Line(- interim_point, p2,- color=df_line_color- )+ group.dx_line = Line(p1, interim_point, color=dx_line_color)+ group.df_line = Line(interim_point, p2, color=df_line_color)group.add(group.dx_line, group.df_line)labels = VGroup()@@ -844,17 +811,13 @@ class GraphScene(Scene):if dx_label is not None:group.dx_label.next_to(- group.dx_line,- np.sign(dx) * DOWN,- buff=group.dx_label.get_height() / 2+ group.dx_line, np.sign(dx) * DOWN, buff=group.dx_label.get_height() / 2)group.dx_label.set_color(group.dx_line.get_color())if df_label is not None:group.df_label.next_to(- group.df_line,- np.sign(dx) * RIGHT,- buff=group.df_label.get_height() / 2+ group.df_line, np.sign(dx) * RIGHT, buff=group.df_label.get_height() / 2)group.df_label.set_color(group.df_line.get_color())@@ -868,7 +831,9 @@ class GraphScene(Scene):return group- def add_T_label(self, x_val, side=RIGHT, label=None, color=WHITE, animated=False, **kwargs):+ def add_T_label(+ self, x_val, side=RIGHT, label=None, color=WHITE, animated=False, **kwargs+ ):"""This method adds to the Scene:-- a Vertical line from the x-axis to the corresponding point on the graph/curve.@@ -907,17 +872,14 @@ class GraphScene(Scene):T_label = TexMobject(label, fill_color=color)T_label.next_to(triangle, DOWN)- v_line = self.get_vertical_line_to_graph(- x_val, self.v_graph,- color=YELLOW- )+ v_line = self.get_vertical_line_to_graph(x_val, self.v_graph, color=YELLOW)if animated:self.play(DrawBorderThenFill(triangle),ShowCreation(v_line),Write(T_label, run_time=1),- **kwargs+ **kwargs,)if np.all(side == LEFT):@@ -930,12 +892,7 @@ class GraphScene(Scene):self.add(self.right_T_label_group, self.right_v_line)def get_animation_integral_bounds_change(- self,- graph,- new_t_min,- new_t_max,- fade_close_to_origin=True,- run_time=1.0+ self, graph, new_t_min, new_t_max, fade_close_to_origin=True, run_time=1.0):"""This method requires a lot of prerequisites:@@ -983,15 +940,11 @@ class GraphScene(Scene):t_max = interpolate(curr_t_max, new_t_max, alpha)new_area = self.get_area(graph, t_min, t_max)- new_left_v_line = self.get_vertical_line_to_graph(- t_min, graph- )+ new_left_v_line = self.get_vertical_line_to_graph(t_min, graph)new_left_v_line.set_color(left_v_line.get_color())left_T_label.move_to(new_left_v_line.get_bottom(), UP)- new_right_v_line = self.get_vertical_line_to_graph(- t_max, graph- )+ new_right_v_line = self.get_vertical_line_to_graph(t_max, graph)new_right_v_line.set_color(right_v_line.get_color())right_T_label.move_to(new_right_v_line.get_bottom(), UP)@@ -1010,12 +963,13 @@ class GraphScene(Scene):return UpdateFromAlphaFunc(group, update_group, run_time=run_time)def animate_secant_slope_group_change(- self, secant_slope_group,+ self,+ secant_slope_group,target_dx=None,target_x=None,run_time=3,added_anims=None,- **anim_kwargs+ **anim_kwargs,):"""This method animates the change of the secant slope group from@@ -1044,8 +998,7 @@ class GraphScene(Scene):NOTE: At least one of target_dx and target_x should be not None."""if target_dx is None and target_x is None:- raise Exception(- "At least one of target_x and target_dx must not be None")+ raise Exception("At least one of target_x and target_dx must not be None")if added_anims is None:added_anims = []@@ -1068,11 +1021,9 @@ class GraphScene(Scene):self.play(UpdateFromAlphaFunc(- secant_slope_group, update_func,- run_time=run_time,- **anim_kwargs+ secant_slope_group, update_func, run_time=run_time, **anim_kwargs),- *added_anims+ *added_anims,)secant_slope_group.kwargs["x"] = target_xsecant_slope_group.kwargs["dx"] = target_dxdiff --git a/manim/scene/moving_camera_scene.py b/manim/scene/moving_camera_scene.pyindex 98f8ed1c6..0cbfb06d5 100644--- a/manim/scene/moving_camera_scene.py+++ b/manim/scene/moving_camera_scene.py@@ -8,9 +8,8 @@ class MovingCameraScene(Scene):This is a Scene, with special configurations and properties thatmake it suitable for cases where the camera must be moved around."""- CONFIG = {- "camera_class": MovingCamera- }++ CONFIG = {"camera_class": MovingCamera}def setup(self):"""@@ -18,7 +17,7 @@ class MovingCameraScene(Scene):to set up the scene for proper use."""Scene.setup(self)- assert(isinstance(self.camera, MovingCamera))+ assert isinstance(self.camera, MovingCamera)self.camera_frame = self.camera.frame# Hmm, this currently relies on the fact that MovingCamera# willd default to a full-sized frame. Is that okay?@@ -44,4 +43,4 @@ class MovingCameraScene(Scene):# When one of these is moving, the camera should# consider all mobjects to be movingreturn list_update(self.mobjects, moving_mobjects)- return moving_mobjects\ No newline at end of file+ return moving_mobjectsdiff --git a/manim/scene/reconfigurable_scene.py b/manim/scene/reconfigurable_scene.pyindex 6976d0657..082b9bddf 100644--- a/manim/scene/reconfigurable_scene.py+++ b/manim/scene/reconfigurable_scene.py@@ -8,6 +8,7 @@ class ReconfigurableScene(Scene):"""Note, this seems to no longer work as intented."""+CONFIG = {"allow_recursion": True,}@@ -20,7 +21,7 @@ class ReconfigurableScene(Scene):self,return_to_original_configuration=True,transformation_kwargs=None,- **new_config+ **new_config,):if transformation_kwargs is None:transformation_kwargs = {}@@ -30,28 +31,23 @@ class ReconfigurableScene(Scene):if not self.allow_recursion:returnalt_scene = self.__class__(- skip_animations=True,- allow_recursion=False,- **new_config+ skip_animations=True, allow_recursion=False, **new_config)alt_state = alt_scene.states[len(self.states) - 1]if return_to_original_configuration:self.clear()self.transition_between_states(- state_copy, alt_state,- **transformation_kwargs+ state_copy, alt_state, **transformation_kwargs)self.transition_between_states(- state_copy, original_state,- **transformation_kwargs+ state_copy, original_state, **transformation_kwargs)self.clear()self.add(*original_state)else:self.transition_between_states(- original_state, alt_state,- **transformation_kwargs+ original_state, alt_state, **transformation_kwargs)self.__dict__.update(new_config)@@ -63,4 +59,4 @@ class ReconfigurableScene(Scene):def transition_between_states(self, start_state, target_state, **kwargs):self.play(Transform(start_state, target_state, **kwargs))- self.wait()\ No newline at end of file+ self.wait()diff --git a/manim/scene/sample_space_scene.py b/manim/scene/sample_space_scene.pyindex 806a9cd2a..f8abf32fd 100644--- a/manim/scene/sample_space_scene.py+++ b/manim/scene/sample_space_scene.py@@ -17,10 +17,7 @@ class SampleSpaceScene(Scene):self.add(self.get_sample_space(**config))def get_division_change_animations(- self, sample_space, parts, p_list,- dimension=1,- new_label_kwargs=None,- **kwargs+ self, sample_space, parts, p_list, dimension=1, new_label_kwargs=None, **kwargs):if new_label_kwargs is None:new_label_kwargs = {}@@ -49,31 +46,36 @@ class SampleSpaceScene(Scene):return animsdef get_horizontal_division_change_animations(self, p_list, **kwargs):- assert(hasattr(self.sample_space, "horizontal_parts"))+ assert hasattr(self.sample_space, "horizontal_parts")return self.get_division_change_animations(- self.sample_space, self.sample_space.horizontal_parts, p_list,+ self.sample_space,+ self.sample_space.horizontal_parts,+ p_list,dimension=1,- **kwargs+ **kwargs,)def get_vertical_division_change_animations(self, p_list, **kwargs):- assert(hasattr(self.sample_space, "vertical_parts"))+ assert hasattr(self.sample_space, "vertical_parts")return self.get_division_change_animations(- self.sample_space, self.sample_space.vertical_parts, p_list,+ self.sample_space,+ self.sample_space.vertical_parts,+ p_list,dimension=0,- **kwargs+ **kwargs,)def get_conditional_change_anims(- self, sub_sample_space_index, value, post_rects=None,- **kwargs+ self, sub_sample_space_index, value, post_rects=None, **kwargs):parts = self.sample_space.horizontal_partssub_sample_space = parts[sub_sample_space_index]anims = self.get_division_change_animations(- sub_sample_space, sub_sample_space.vertical_parts, value,+ sub_sample_space,+ sub_sample_space.vertical_parts,+ value,dimension=0,- **kwargs+ **kwargs,)if post_rects is not None:anims += self.get_posterior_rectangle_change_anims(post_rects)@@ -86,30 +88,22 @@ class SampleSpaceScene(Scene):return self.get_conditional_change_anims(1, *args, **kwargs)def get_prior_rectangles(self):- return VGroup(*[- self.sample_space.horizontal_parts[i].vertical_parts[0]- for i in range(2)- ])+ return VGroup(+ *[self.sample_space.horizontal_parts[i].vertical_parts[0] for i in range(2)]+ )def get_posterior_rectangles(self, buff=MED_LARGE_BUFF):prior_rects = self.get_prior_rectangles()- areas = [- rect.get_width() * rect.get_height()- for rect in prior_rects- ]+ areas = [rect.get_width() * rect.get_height() for rect in prior_rects]total_area = sum(areas)total_height = prior_rects.get_height()post_rects = prior_rects.copy()for rect, area in zip(post_rects, areas):rect.stretch_to_fit_height(total_height * area / total_area)- rect.stretch_to_fit_width(- area / rect.get_height()- )+ rect.stretch_to_fit_width(area / rect.get_height())post_rects.arrange(DOWN, buff=0)- post_rects.next_to(- self.sample_space, RIGHT, buff- )+ post_rects.next_to(self.sample_space, RIGHT, buff)return post_rectsdef get_posterior_rectangle_braces_and_labels(@@ -137,7 +131,5 @@ class SampleSpaceScene(Scene):anims = [UpdateFromFunc(post_rects, update_rects)]if hasattr(post_rects, "braces"):- anims += list(map(Animation, [- post_rects.labels, post_rects.braces- ]))- return anims\ No newline at end of file+ anims += list(map(Animation, [post_rects.labels, post_rects.braces]))+ return animsdiff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex da5e2179d..a1e85e83d 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -43,6 +43,7 @@ class Scene(Container):time: time elapsed since initialisation of scene.random_seed: The seed with which all random operations are done."""+CONFIG = {"camera_class": Camera,"skip_animations": False,@@ -53,16 +54,14 @@ class Scene(Container):def __init__(self, **kwargs):Container.__init__(self, **kwargs)self.camera = self.camera_class(**camera_config)- self.file_writer = SceneFileWriter(- self, **file_writer_config,- )+ self.file_writer = SceneFileWriter(self, **file_writer_config,)self.mobjects = []# TODO, remove need for foreground mobjectsself.foreground_mobjects = []self.num_plays = 0self.time = 0- self.original_skipping_status = file_writer_config['skip_animations']+ self.original_skipping_status = file_writer_config["skip_animations"]if self.random_seed is not None:random.seed(self.random_seed)np.random.seed(self.random_seed)@@ -205,19 +204,22 @@ class Scene(Container):"""self.camera.reset()- def capture_mobjects_in_camera(self, mobjects, **kwargs): #TODO Add more detail to docstring.+ def capture_mobjects_in_camera(+ self, mobjects, **kwargs+ ): # TODO Add more detail to docstring."""This method is used internally."""self.camera.capture_mobjects(mobjects, **kwargs)- def update_frame( #TODO Description in Docstring- self,- mobjects=None,- background=None,- include_submobjects=True,- ignore_skipping=True,- **kwargs):+ def update_frame( # TODO Description in Docstring+ self,+ mobjects=None,+ background=None,+ include_submobjects=True,+ ignore_skipping=True,+ **kwargs,+ ):"""Parameters:-----------@@ -234,13 +236,10 @@ class Scene(Container):**kwargs"""- if file_writer_config['skip_animations'] and not ignore_skipping:+ if file_writer_config["skip_animations"] and not ignore_skipping:returnif mobjects is None:- mobjects = list_update(- self.mobjects,- self.foreground_mobjects,- )+ mobjects = list_update(self.mobjects, self.foreground_mobjects,)if background is not None:self.set_camera_pixel_array(background)else:@@ -253,6 +252,7 @@ class Scene(Container):self.update_frame()self.set_camera(Camera(self.get_frame()))self.clear()+###def update_mobjects(self, dt):@@ -276,10 +276,9 @@ class Scene(Container):-------bool"""- return self.always_update_mobjects or any([- mob.has_time_based_updater()- for mob in self.get_mobject_family_members()- ])+ return self.always_update_mobjects or any(+ [mob.has_time_based_updater() for mob in self.get_mobject_family_members()]+ )###@@ -323,11 +322,9 @@ class Scene(Container):families = [m.get_family() for m in mobjects]def is_top_level(mobject):- num_families = sum([- (mobject in family)- for family in families- ])+ num_families = sum([(mobject in family) for family in families])return num_families == 1+return list(filter(is_top_level, mobjects))def get_mobject_family_members(self):@@ -371,10 +368,7 @@ class Scene(Container):e.g. to add all mobjects defined up to a point,call self.add_mobjects_among(locals().values())"""- self.add(*filter(- lambda m: isinstance(m, Mobject),- values- ))+ self.add(*filter(lambda m: isinstance(m, Mobject), values))return selfdef remove(self, *mobjects):@@ -392,9 +386,9 @@ class Scene(Container):self.restructure_mobjects(mobjects, list_name, False)return self- def restructure_mobjects(self, to_remove,- mobject_list_name="mobjects",- extract_families=True):+ def restructure_mobjects(+ self, to_remove, mobject_list_name="mobjects", extract_families=True+ ):"""tl:wrIf your scene has a Group(), and you removed a mobject from the Group,@@ -460,6 +454,7 @@ class Scene(Container):add_safe_mobjects_from_list(mob.submobjects, intersect)else:new_mobjects.append(mob)+add_safe_mobjects_from_list(mobjects, set(to_remove))return new_mobjects@@ -479,10 +474,7 @@ class Scene(Container):SceneThe Scene, with the foreground mobjects added."""- self.foreground_mobjects = list_update(- self.foreground_mobjects,- mobjects- )+ self.foreground_mobjects = list_update(self.foreground_mobjects, mobjects)self.add(*mobjects)return self@@ -642,13 +634,15 @@ class Scene(Container):update_possibilities = [mob in animation_mobjects,len(mob.get_family_updaters()) > 0,- mob in self.foreground_mobjects+ mob in self.foreground_mobjects,]if any(update_possibilities):return mobjects[i:]return []- def get_time_progression(self, run_time, n_iterations=None, override_skip_animations=False):+ def get_time_progression(+ self, run_time, n_iterations=None, override_skip_animations=False+ ):"""You will hardly use this when making your own animations.This method is for Manim's internal use.@@ -675,15 +669,16 @@ class Scene(Container):ProgressDisplayThe CommandLine Progress Bar."""- if file_writer_config['skip_animations'] and not override_skip_animations:+ if file_writer_config["skip_animations"] and not override_skip_animations:times = [run_time]else:step = 1 / self.camera.frame_ratetimes = np.arange(0, run_time, step)time_progression = ProgressDisplay(- times, total=n_iterations,- leave=file_writer_config['leave_progress_bars'],- ascii=True if platform.system() == 'Windows' else None+ times,+ total=n_iterations,+ leave=file_writer_config["leave_progress_bars"],+ ascii=True if platform.system() == "Windows" else None,)return time_progression@@ -727,11 +722,15 @@ class Scene(Container):"""run_time = self.get_run_time(animations)time_progression = self.get_time_progression(run_time)- time_progression.set_description("".join([- "Animation {}: ".format(self.num_plays),- str(animations[0]),- (", etc." if len(animations) > 1 else ""),- ]))+ time_progression.set_description(+ "".join(+ [+ "Animation {}: ".format(self.num_plays),+ str(animations[0]),+ (", etc." if len(animations) > 1 else ""),+ ]+ )+ )return time_progressiondef compile_play_args_to_animation_list(self, *args, **kwargs):@@ -772,14 +771,14 @@ class Scene(Container):else:mobject.generate_target()#- if len(state["method_args"]) > 0 and isinstance(state["method_args"][-1], dict):+ if len(state["method_args"]) > 0 and isinstance(+ state["method_args"][-1], dict+ ):method_kwargs = state["method_args"].pop()else:method_kwargs = {}state["curr_method"].__func__(- mobject.target,- *state["method_args"],- **method_kwargs+ mobject.target, *state["method_args"], **method_kwargs)animations.append(MoveToTarget(mobject))state["last_method"] = state["curr_method"]@@ -796,10 +795,12 @@ class Scene(Container):elif state["curr_method"] is not None:state["method_args"].append(arg)elif isinstance(arg, Mobject):- raise Exception("""+ raise Exception(+ """I think you may have invoked a methodyou meant to pass in as a Scene.play argument- """)+ """+ )else:raise Exception("Invalid play arguments")compile_method(state)@@ -820,12 +821,12 @@ class Scene(Container):raises an EndSceneEarlyException if they don't correspond."""- if file_writer_config['from_animation_number']:- if self.num_plays == file_writer_config['from_animation_number']:- file_writer_config['skip_animations'] = False- if file_writer_config['upto_animation_number']:- if self.num_plays >= file_writer_config['upto_animation_number']:- file_writer_config['skip_animations'] = True+ if file_writer_config["from_animation_number"]:+ if self.num_plays == file_writer_config["from_animation_number"]:+ file_writer_config["skip_animations"] = False+ if file_writer_config["upto_animation_number"]:+ if self.num_plays >= file_writer_config["upto_animation_number"]:+ file_writer_config["skip_animations"] = Trueraise EndSceneEarlyException()def handle_play_like_call(func):@@ -848,13 +849,15 @@ class Scene(Container):The play() like function that can now writeto the video file stream."""+def wrapper(self, *args, **kwargs):self.update_skipping_status()- allow_write = not file_writer_config['skip_animations']+ allow_write = not file_writer_config["skip_animations"]self.file_writer.begin_animation(allow_write)func(self, *args, **kwargs)self.file_writer.end_animation(allow_write)self.num_plays += 1+return wrapperdef begin_animations(self, animations):@@ -920,10 +923,8 @@ class Scene(Container):for animation in animations:animation.finish()animation.clean_up_from_scene(self)- self.mobjects_from_last_animation = [- anim.mobject for anim in animations- ]- if file_writer_config['skip_animations']:+ self.mobjects_from_last_animation = [anim.mobject for anim in animations]+ if file_writer_config["skip_animations"]:# TODO, run this call in for each animation?self.update_mobjects(self.get_run_time(animations))else:@@ -944,9 +945,7 @@ class Scene(Container):if len(args) == 0:warnings.warn("Called Scene.play with no animations")return- animations = self.compile_play_args_to_animation_list(- *args, **kwargs- )+ animations = self.compile_play_args_to_animation_list(*args, **kwargs)self.begin_animations(animations)self.progress_through_animations(animations)self.finish_animations(animations)@@ -1020,16 +1019,14 @@ class Scene(Container):time_progression = self.get_time_progression(duration,n_iterations=-1, # So it doesn't show % progress- override_skip_animations=True+ override_skip_animations=True,)time_progression.set_description("Waiting for {}".format(stop_condition.__name__))else:time_progression = self.get_time_progression(duration)- time_progression.set_description(- "Waiting {}".format(self.num_plays)- )+ time_progression.set_description("Waiting {}".format(self.num_plays))return time_progression@handle_play_like_call@@ -1066,7 +1063,7 @@ class Scene(Container):if stop_condition is not None and stop_condition():time_progression.close()break- elif file_writer_config['skip_animations']:+ elif file_writer_config["skip_animations"]:# Do nothingreturn selfelse:@@ -1135,7 +1132,7 @@ class Scene(Container):"""dt = 1 / self.camera.frame_rateself.increment_time(len(frames) * dt)- if file_writer_config['skip_animations']:+ if file_writer_config["skip_animations"]:returnfor frame in frames:self.file_writer.write_frame(frame)diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex aaea1d2f1..1c623f73e 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -52,42 +52,38 @@ class SceneFileWriter(object):"""module_directory = self.get_default_module_directory()scene_name = self.get_default_scene_name()- if file_writer_config['save_last_frame'] or file_writer_config['save_pngs']:- if file_writer_config['media_dir'] != "":- image_dir = guarantee_existence(os.path.join(- file_writer_config['media_dir'],- "images",- module_directory,- ))+ if file_writer_config["save_last_frame"] or file_writer_config["save_pngs"]:+ if file_writer_config["media_dir"] != "":+ image_dir = guarantee_existence(+ os.path.join(+ file_writer_config["media_dir"], "images", module_directory,+ )+ )self.image_file_path = os.path.join(- image_dir,- add_extension_if_not_present(scene_name, ".png")+ image_dir, add_extension_if_not_present(scene_name, ".png"))- if file_writer_config['write_to_movie']:- if file_writer_config['video_dir']:- movie_dir = guarantee_existence(os.path.join(- file_writer_config['video_dir'],- module_directory,- self.get_resolution_directory(),- ))+ if file_writer_config["write_to_movie"]:+ if file_writer_config["video_dir"]:+ movie_dir = guarantee_existence(+ os.path.join(+ file_writer_config["video_dir"],+ module_directory,+ self.get_resolution_directory(),+ )+ )self.movie_file_path = os.path.join(movie_dir,add_extension_if_not_present(- scene_name, file_writer_config['movie_file_extension']- )+ scene_name, file_writer_config["movie_file_extension"]+ ),)self.gif_file_path = os.path.join(- movie_dir,- add_extension_if_not_present(- scene_name, GIF_FILE_EXTENSION- )+ movie_dir, add_extension_if_not_present(scene_name, GIF_FILE_EXTENSION)+ )+ self.partial_movie_directory = guarantee_existence(+ os.path.join(movie_dir, "partial_movie_files", scene_name,))- self.partial_movie_directory = guarantee_existence(os.path.join(- movie_dir,- "partial_movie_files",- scene_name,- ))def get_default_module_directory(self):"""@@ -99,7 +95,7 @@ class SceneFileWriter(object):strThe name of the directory."""- filename = os.path.basename(file_writer_config['input_file'])+ filename = os.path.basename(file_writer_config["input_file"])root, _ = os.path.splitext(filename)return root@@ -115,8 +111,8 @@ class SceneFileWriter(object):strThe default scene name."""- fn = file_writer_config['output_file']- return (fn if fn else self.scene.__class__.__name__)+ fn = file_writer_config["output_file"]+ return fn if fn else self.scene.__class__.__name__def get_resolution_directory(self):"""@@ -142,9 +138,7 @@ class SceneFileWriter(object):"""pixel_height = self.scene.camera.pixel_heightframe_rate = self.scene.camera.frame_rate- return "{}p{}".format(- pixel_height, frame_rate- )+ return "{}p{}".format(pixel_height, frame_rate)# Directory gettersdef get_image_file_path(self):@@ -177,9 +171,8 @@ class SceneFileWriter(object):result = os.path.join(self.partial_movie_directory,"{:05}{}".format(- self.scene.num_plays,- file_writer_config['movie_file_extension'],- )+ self.scene.num_plays, file_writer_config["movie_file_extension"],+ ),)return result@@ -207,9 +200,7 @@ class SceneFileWriter(object):"""self.audio_segment = AudioSegment.silent()- def add_audio_segment(self, new_segment,- time=None,- gain_to_background=None):+ def add_audio_segment(self, new_segment, time=None, gain_to_background=None):"""This method adds an audio segment from anAudioSegment type object and suitable parameters.@@ -240,8 +231,7 @@ class SceneFileWriter(object):diff = new_end - curr_endif diff > 0:segment = segment.append(- AudioSegment.silent(int(np.ceil(diff * 1000))),- crossfade=0,+ AudioSegment.silent(int(np.ceil(diff * 1000))), crossfade=0,)self.audio_segment = segment.overlay(new_segment,@@ -286,7 +276,7 @@ class SceneFileWriter(object):allow_write : bool, optionalWhether or not to write to a video file."""- if file_writer_config['write_to_movie'] and allow_write:+ if file_writer_config["write_to_movie"] and allow_write:self.open_movie_pipe()def end_animation(self, allow_write=False):@@ -299,7 +289,7 @@ class SceneFileWriter(object):allow_write : bool, optionalWhether or not to write to a video file."""- if file_writer_config['write_to_movie'] and allow_write:+ if file_writer_config["write_to_movie"] and allow_write:self.close_movie_pipe()def write_frame(self, frame):@@ -312,11 +302,11 @@ class SceneFileWriter(object):frame : np.arrayPixel array of the frame."""- if file_writer_config['write_to_movie']:+ if file_writer_config["write_to_movie"]:self.writing_process.stdin.write(frame.tostring())- if file_writer_config['save_pngs']:+ if file_writer_config["save_pngs"]:path, extension = os.path.splitext(self.image_file_path)- Image.fromarray(frame).save(f'{path}{self.frame_count}{extension}')+ Image.fromarray(frame).save(f"{path}{self.frame_count}{extension}")self.frame_count += 1def save_final_image(self, image):@@ -357,11 +347,11 @@ class SceneFileWriter(object):If save_last_frame is True, saves the lastframe in the default image directory."""- if file_writer_config['write_to_movie']:+ if file_writer_config["write_to_movie"]:if hasattr(self, "writing_process"):self.writing_process.terminate()self.combine_movie_files()- if file_writer_config['save_last_frame']:+ if file_writer_config["save_last_frame"]:self.scene.update_frame(ignore_skipping=True)self.save_final_image(self.scene.get_image())@@ -372,9 +362,11 @@ class SceneFileWriter(object):buffer."""file_path = self.get_next_partial_movie_path()- temp_file_path = (os.path.splitext(file_path)[0]- + '_temp'- + file_writer_config['movie_file_extension'])+ temp_file_path = (+ os.path.splitext(file_path)[0]+ + "_temp"+ + file_writer_config["movie_file_extension"]+ )self.partial_movie_file_path = file_pathself.temp_partial_movie_file_path = temp_file_path@@ -384,27 +376,36 @@ class SceneFileWriter(object):command = [FFMPEG_BIN,- '-y', # overwrite output file if it exists- '-f', 'rawvideo',- '-s', '%dx%d' % (width, height), # size of one frame- '-pix_fmt', 'rgba',- '-r', str(fps), # frames per second- '-i', '-', # The imput comes from a pipe- '-an', # Tells FFMPEG not to expect any audio- '-loglevel', 'error',+ "-y", # overwrite output file if it exists+ "-f",+ "rawvideo",+ "-s",+ "%dx%d" % (width, height), # size of one frame+ "-pix_fmt",+ "rgba",+ "-r",+ str(fps), # frames per second+ "-i",+ "-", # The imput comes from a pipe+ "-an", # Tells FFMPEG not to expect any audio+ "-loglevel",+ "error",]# TODO, the test for a transparent background should not be based on# the file extension.- if file_writer_config['movie_file_extension'] == ".mov":+ if file_writer_config["movie_file_extension"] == ".mov":# This is if the background of the exported# video should be transparent.command += [- '-vcodec', 'qtrle',+ "-vcodec",+ "qtrle",]else:command += [- '-vcodec', 'libx264',- '-pix_fmt', 'yuv420p',+ "-vcodec",+ "libx264",+ "-pix_fmt",+ "yuv420p",]command += [temp_file_path]self.writing_process = subprocess.Popen(command, stdin=subprocess.PIPE)@@ -418,8 +419,7 @@ class SceneFileWriter(object):self.writing_process.stdin.close()self.writing_process.wait()shutil.move(- self.temp_partial_movie_file_path,- self.partial_movie_file_path,+ self.temp_partial_movie_file_path, self.partial_movie_file_path,)def combine_movie_files(self):@@ -437,17 +437,16 @@ class SceneFileWriter(object):# single piece.kwargs = {"remove_non_integer_files": True,- "extension": file_writer_config['movie_file_extension'],+ "extension": file_writer_config["movie_file_extension"],}- if file_writer_config['from_animation_number'] is not None:- kwargs["min_index"] = file_writer_config['from_animation_number']- if file_writer_config['upto_animation_number'] is not None:- kwargs["max_index"] = file_writer_config['upto_animation_number']+ if file_writer_config["from_animation_number"] is not None:+ kwargs["min_index"] = file_writer_config["from_animation_number"]+ if file_writer_config["upto_animation_number"] is not None:+ kwargs["max_index"] = file_writer_config["upto_animation_number"]else:kwargs["remove_indices_greater_than"] = self.scene.num_plays - 1partial_movie_files = get_sorted_integer_files(- self.partial_movie_directory,- **kwargs+ self.partial_movie_directory, **kwargs)if len(partial_movie_files) == 0:logger.error("No animations in this scene")@@ -456,65 +455,70 @@ class SceneFileWriter(object):# Write a file partial_file_list.txt containing all# partial movie filesfile_list = os.path.join(- self.partial_movie_directory,- "partial_movie_file_list.txt"+ self.partial_movie_directory, "partial_movie_file_list.txt")- with open(file_list, 'w') as fp:+ with open(file_list, "w") as fp:for pf_path in partial_movie_files:- if os.name == 'nt':- pf_path = pf_path.replace('\\', '/')- fp.write("file \'file:{}\'\n".format(pf_path))+ if os.name == "nt":+ pf_path = pf_path.replace("\\", "/")+ fp.write("file 'file:{}'\n".format(pf_path))movie_file_path = self.get_movie_file_path()commands = [FFMPEG_BIN,- '-y', # overwrite output file if it exists- '-f', 'concat',- '-safe', '0',- '-i', file_list,- '-loglevel', 'error',+ "-y", # overwrite output file if it exists+ "-f",+ "concat",+ "-safe",+ "0",+ "-i",+ file_list,+ "-loglevel",+ "error",]if self.write_to_movie:- commands += [- '-c', 'copy',- movie_file_path- ]+ commands += ["-c", "copy", movie_file_path]if self.save_as_gif:- commands += [- self.gif_file_path- ]+ commands += [self.gif_file_path]if not self.includes_sound:- commands.insert(-1, '-an')+ commands.insert(-1, "-an")combine_process = subprocess.Popen(commands)combine_process.wait()if self.includes_sound:sound_file_path = movie_file_path.replace(- file_writer_config['movie_file_extension'], ".wav"+ file_writer_config["movie_file_extension"], ".wav")# Makes sure sound file length will match video fileself.add_audio_segment(AudioSegment.silent(0))self.audio_segment.export(- sound_file_path,- bitrate='312k',+ sound_file_path, bitrate="312k",)temp_file_path = movie_file_path.replace(".", "_temp.")commands = [FFMPEG_BIN,- "-i", movie_file_path,- "-i", sound_file_path,- '-y', # overwrite output file if it exists- "-c:v", "copy",- "-c:a", "aac",- "-b:a", "320k",+ "-i",+ movie_file_path,+ "-i",+ sound_file_path,+ "-y", # overwrite output file if it exists+ "-c:v",+ "copy",+ "-c:a",+ "aac",+ "-b:a",+ "320k",# select video stream from first file- "-map", "0:v:0",+ "-map",+ "0:v:0",# select audio stream from second file- "-map", "1:a:0",- '-loglevel', 'error',+ "-map",+ "1:a:0",+ "-loglevel",+ "error",# "-shortest",temp_file_path,]diff --git a/manim/scene/three_d_scene.py b/manim/scene/three_d_scene.pyindex bbb226d59..60ef0831d 100644--- a/manim/scene/three_d_scene.py+++ b/manim/scene/three_d_scene.py@@ -17,13 +17,14 @@ class ThreeDScene(Scene):This is a Scene, with special configurations and properties thatmake it suitable for Three Dimensional Scenes."""+CONFIG = {"camera_class": ThreeDCamera,"ambient_camera_rotation": None,"default_angled_camera_orientation_kwargs": {"phi": 70 * DEGREES,"theta": -135 * DEGREES,- }+ },}def set_camera_orientation(self, phi=None, theta=None, distance=None, gamma=None):@@ -78,14 +79,16 @@ class ThreeDScene(Scene):self.camera.theta_tracker.clear_updaters()self.remove(self.camera.theta_tracker)- def move_camera(self,- phi=None,- theta=None,- distance=None,- gamma=None,- frame_center=None,- added_anims=[],- **kwargs):+ def move_camera(+ self,+ phi=None,+ theta=None,+ distance=None,+ gamma=None,+ frame_center=None,+ added_anims=[],+ **kwargs,+ ):"""This method animates the movement of the camerato the given spherical coordinates.@@ -120,14 +123,9 @@ class ThreeDScene(Scene):]for value, tracker in value_tracker_pairs:if value is not None:- anims.append(- ApplyMethod(tracker.set_value, value, **kwargs)- )+ anims.append(ApplyMethod(tracker.set_value, value, **kwargs))if frame_center is not None:- anims.append(ApplyMethod(- self.camera.frame_center.move_to,- frame_center- ))+ anims.append(ApplyMethod(self.camera.frame_center.move_to, frame_center))self.play(*anims + added_anims)@@ -238,6 +236,7 @@ class SpecialThreeDScene(ThreeDScene):except if rendering in low quality.Some default params for Spheres and Axes have been added."""+CONFIG = {"cut_axes_at_radius": True,"camera_config": {@@ -251,12 +250,9 @@ class SpecialThreeDScene(ThreeDScene):"tick_frequency": 1,"numbers_with_elongated_ticks": [0, 1, 2],"stroke_width": 2,- }- },- "sphere_config": {- "radius": 2,- "resolution": (24, 48),+ },},+ "sphere_config": {"radius": 2, "resolution": (24, 48),},"default_angled_camera_position": {"phi": 70 * DEGREES,"theta": -110 * DEGREES,@@ -264,21 +260,15 @@ class SpecialThreeDScene(ThreeDScene):# 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),- }- }+ "camera_config": {"should_apply_shading": False,},+ "three_d_axes_config": {"num_axis_pieces": 1,},+ "sphere_config": {"resolution": (12, 24),},+ },}def __init__(self, **kwargs):digest_config(self, kwargs)- if self.camera_config["pixel_width"] == config['CAMERA_CONFIG']['PIXEL_WIDTH']:+ if self.camera_config["pixel_width"] == config["CAMERA_CONFIG"]["PIXEL_WIDTH"]:config = {}else:config = self.low_quality_config@@ -300,17 +290,13 @@ class SpecialThreeDScene(ThreeDScene):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),- )+ new_pieces = VGroup(Line(p0, p1), Line(p1, p2), Line(p2, p3),)for piece in new_pieces:piece.shade_in_3d = Truenew_pieces.match_style(axis.pieces)axis.pieces.submobjects = new_pieces.submobjectsfor tick in axis.tick_marks:- tick.add(VectorizedPoint(- 1.5 * tick.get_center(),- ))+ tick.add(VectorizedPoint(1.5 * tick.get_center(),))return axesdef get_sphere(self, **kwargs):@@ -347,6 +333,4 @@ class SpecialThreeDScene(ThreeDScene):"""Sets the camera to its default position."""- self.set_camera_orientation(- **self.default_angled_camera_position- )+ self.set_camera_orientation(**self.default_angled_camera_position)diff --git a/manim/scene/vector_space_scene.py b/manim/scene/vector_space_scene.pyindex ac860857b..b285fcc7c 100644--- a/manim/scene/vector_space_scene.py+++ b/manim/scene/vector_space_scene.py@@ -43,9 +43,7 @@ Z_COLOR = BLUE_D# Also, methods I would have thought of as getters, like coords_to_vector, are# actually doing a lot of animating.class VectorScene(Scene):- CONFIG = {- "basis_vector_stroke_width": 6- }+ CONFIG = {"basis_vector_stroke_width": 6}def add_plane(self, animate=False, **kwargs):"""@@ -127,7 +125,7 @@ class VectorScene(Scene):self.plane.coords_to_point(0, 0),self.plane.coords_to_point(*numerical_vector[:2]),buff=0,- **kwargs+ **kwargs,)def add_vector(self, vector, color=YELLOW, animate=True, **kwargs):@@ -210,17 +208,12 @@ class VectorScene(Scene):VGroupVGroup of the Vector Mobjects representing the basis vectors."""- return VGroup(*[- Vector(- vect,- color=color,- stroke_width=self.basis_vector_stroke_width- )- for vect, color in [- ([1, 0], i_hat_color),- ([0, 1], j_hat_color)+ return VGroup(+ *[+ Vector(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):"""@@ -239,24 +232,28 @@ class VectorScene(Scene):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),+ 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, label,- at_tip=False,- direction="left",- rotate=False,- color=None,- label_scale_factor=VECTOR_LABEL_SCALE_FACTOR):+ def get_vector_label(+ self,+ vector,+ label,+ at_tip=False,+ direction="left",+ rotate=False,+ color=None,+ label_scale_factor=VECTOR_LABEL_SCALE_FACTOR,+ ):"""Returns naming labels for the passed vector.@@ -338,12 +335,16 @@ class VectorScene(Scene):self.add(label)return label- def position_x_coordinate(self, x_coord, x_line, vector): #TODO Write DocStrings for this.+ def position_x_coordinate(+ self, x_coord, x_line, vector+ ): # 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, y_line, vector): #TODO Write DocStrings for this.+ def position_y_coordinate(+ self, y_coord, y_line, vector+ ): # 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@@ -383,17 +384,17 @@ class VectorScene(Scene):self.play(Write(array, run_time=1))self.wait()- self.play(ApplyFunction(- lambda x: self.position_x_coordinate(x, x_line, vector),- x_coord- ))+ self.play(+ ApplyFunction(+ lambda x: self.position_x_coordinate(x, x_line, vector), x_coord+ )+ )self.play(ShowCreation(x_line))self.play(ApplyFunction(- lambda y: self.position_y_coordinate(y, y_line, vector),- y_coord+ lambda y: self.position_y_coordinate(y, y_line, vector), y_coord),- FadeOut(array.get_brackets())+ FadeOut(array.get_brackets()),)y_coord, brackets = self.get_mobjects_from_last_animation()self.play(ShowCreation(y_line))@@ -438,26 +439,14 @@ class VectorScene(Scene):x_line.set_color(X_COLOR)y_line.set_color(Y_COLOR)x_coord, y_coord = array.get_mob_matrix().flatten()- 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- )+ 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(ShowCreation(arrow))- self.play(- ShowCreation(x_line),- Write(x_coord_start),- run_time=1- )- self.play(- ShowCreation(y_line),- Write(y_coord_start),- run_time=1- )+ self.play(ShowCreation(x_line), Write(x_coord_start), run_time=1)+ self.play(ShowCreation(y_line), Write(y_coord_start), run_time=1)self.wait()self.play(Transform(x_coord_start, x_coord, lag_ratio=0),@@ -489,23 +478,21 @@ class VectorScene(Scene):vector = vector.get_end() - vector.get_start()elif len(vector) == 2:vector = np.append(np.array(vector), 0.0)- x_max = int(config['frame_x_radius'] + abs(vector[0]))- y_max = int(config['frame_y_radius'] + abs(vector[1]))- dots = VMobject(*[- Dot(x * RIGHT + y * UP)- for x in range(-x_max, x_max)- for y in range(-y_max, y_max)- ])+ x_max = int(config["frame_x_radius"] + abs(vector[0]))+ y_max = int(config["frame_y_radius"] + abs(vector[1]))+ dots = VMobject(+ *[+ 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 / 2).set_fill(WHITE, 1)dots_end = dots.copy().shift(vector)- self.play(Transform(- dots, dots_halfway, rate_func=rush_into- ))- self.play(Transform(- dots, dots_end, rate_func=rush_from- ))+ self.play(Transform(dots, dots_halfway, rate_func=rush_into))+ self.play(Transform(dots, dots_end, rate_func=rush_from))self.remove(dots)@@ -514,28 +501,22 @@ class LinearTransformationScene(VectorScene):This scene contains special methods that make itespecially suitable for showing Linear Transformations."""+CONFIG = {"include_background_plane": True,"include_foreground_plane": True,"foreground_plane_kwargs": {- "x_max": config['frame_width'] / 2,- "x_min": -config['frame_width'] / 2,- "y_max": config['frame_width'] / 2,- "y_min": -config['frame_width'] / 2,- "faded_line_ratio": 0+ "x_max": config["frame_width"] / 2,+ "x_min": -config["frame_width"] / 2,+ "y_max": config["frame_width"] / 2,+ "y_min": -config["frame_width"] / 2,+ "faded_line_ratio": 0,},"background_plane_kwargs": {"color": GREY,- "axis_config": {- "stroke_color": LIGHT_GREY,- },- "axis_config": {- "color": GREY,- },- "background_line_style": {- "stroke_color": GREY,- "stroke_width": 1,- },+ "axis_config": {"stroke_color": LIGHT_GREY,},+ "axis_config": {"color": GREY,},+ "background_line_style": {"stroke_color": GREY, "stroke_width": 1,},},"show_coordinates": False,"show_basis_vectors": True,@@ -559,9 +540,7 @@ class LinearTransformationScene(VectorScene):self.moving_mobjects = []self.t_matrix = np.array(self.t_matrix)- self.background_plane = NumberPlane(- **self.background_plane_kwargs- )+ self.background_plane = NumberPlane(**self.background_plane_kwargs)if self.show_coordinates:self.background_plane.add_coordinates()@@ -572,8 +551,7 @@ class LinearTransformationScene(VectorScene):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,+ 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@@ -681,7 +659,7 @@ class LinearTransformationScene(VectorScene):stroke_color=color,stroke_width=stroke_width,fill_color=color,- fill_opacity=opacity+ fill_opacity=opacity,)square.move_to(self.plane.coords_to_point(0, 0), DL)return square@@ -708,8 +686,7 @@ class LinearTransformationScene(VectorScene):square = self.get_unit_square(**kwargs)if animate:self.play(- DrawBorderThenFill(square),- Animation(Group(*self.moving_vectors))+ DrawBorderThenFill(square), Animation(Group(*self.moving_vectors)))self.add_transformable_mobject(square)self.bring_to_front(*self.moving_vectors)@@ -740,9 +717,7 @@ class LinearTransformationScene(VectorScene):ArrowThe arrow representing the vector."""- vector = VectorScene.add_vector(- self, vector, color=color, **kwargs- )+ vector = VectorScene.add_vector(self, vector, color=color, **kwargs)self.moving_vectors.append(vector)return vector@@ -770,10 +745,8 @@ class LinearTransformationScene(VectorScene):return coordsdef add_transformable_label(- self, vector, label,- transformation_name="L",- new_label=None,- **kwargs):+ self, vector, label, transformation_name="L", new_label=None, **kwargs+ ):"""Method for creating, and animating the addition ofa transformable label for the vector.@@ -806,7 +779,7 @@ class LinearTransformationScene(VectorScene):else:label_mob.target_text = "%s(%s)" % (transformation_name,- label_mob.get_tex_string()+ label_mob.get_tex_string(),)label_mob.vector = vectorlabel_mob.kwargs = kwargs@@ -963,9 +936,7 @@ class LinearTransformationScene(VectorScene):The animation of the movement."""for l in self.transformable_labels:- l.target = self.get_vector_label(- l.vector.target, l.target_text, **l.kwargs- )+ l.target = self.get_vector_label(l.vector.target, l.target_text, **l.kwargs)return self.get_piece_movement(self.transformable_labels)def apply_matrix(self, matrix, **kwargs):@@ -1013,10 +984,9 @@ class LinearTransformationScene(VectorScene):"""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- ])+ net_rotation = np.mean(+ [angle_of_vector(func(RIGHT)), angle_of_vector(func(UP)) - np.pi / 2]+ )kwargs["path_arc"] = net_rotationself.apply_function(func, **kwargs)@@ -1073,15 +1043,17 @@ class LinearTransformationScene(VectorScene):"""if "run_time" not in kwargs:kwargs["run_time"] = 3- anims = [- ApplyPointwiseFunction(function, t_mob)- 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+ anims = (+ [+ ApplyPointwiseFunction(function, t_mob)+ 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)diff --git a/manim/scene/zoomed_scene.py b/manim/scene/zoomed_scene.pyindex 5c88794b1..967b607ae 100644--- a/manim/scene/zoomed_scene.py+++ b/manim/scene/zoomed_scene.py@@ -16,6 +16,7 @@ class ZoomedScene(MovingCameraScene):a particular part of the scene must be zoomed in on and displayedseparately."""+CONFIG = {"camera_class": MultiCamera,"zoomed_display_height": 3,@@ -57,8 +58,7 @@ class ZoomedScene(MovingCameraScene):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_display_corner, buff=self.zoomed_display_corner_buff)self.zoomed_camera = zoomed_camera@@ -81,8 +81,7 @@ class ZoomedScene(MovingCameraScene):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,+ self.zoomed_camera.frame, self.zoomed_display,)def get_zoom_in_animation(self, run_time=2, **kwargs):@@ -139,6 +138,5 @@ class ZoomedScene(MovingCameraScene):The zoom factor."""return fdiv(- self.zoomed_camera.frame.get_height(),- self.zoomed_display.get_height()+ self.zoomed_camera.frame.get_height(), self.zoomed_display.get_height())diff --git a/manim/utils/bezier.py b/manim/utils/bezier.pyindex d49f14b7a..c86eab566 100644--- a/manim/utils/bezier.py+++ b/manim/utils/bezier.py@@ -8,10 +8,12 @@ CLOSED_THRESHOLD = 0.001def bezier(points):n = len(points) - 1- return lambda t: sum([- ((1 - t)**(n - k)) * (t**k) * choose(n, k) * point- for k, point in enumerate(points)- ])+ return lambda t: sum(+ [+ ((1 - t) ** (n - k)) * (t ** k) * choose(n, k) * point+ for k, point in enumerate(points)+ ]+ )def partial_bezier_points(points, a, b):@@ -27,19 +29,14 @@ def partial_bezier_points(points, a, b):if a == 1:return [points[-1]] * len(points)- a_to_1 = np.array([- bezier(points[i:])(a)- for i in range(len(points))- ])- end_prop = (b - a) / (1. - a)- return np.array([- bezier(a_to_1[:i + 1])(end_prop)- for i in range(len(points))- ])+ a_to_1 = np.array([bezier(points[i:])(a) for i in range(len(points))])+ end_prop = (b - a) / (1.0 - a)+ return np.array([bezier(a_to_1[: i + 1])(end_prop) for i in range(len(points))])# Linear interpolation variants+def interpolate(start, end, alpha):return (1 - alpha) * start + alpha * end@@ -75,8 +72,7 @@ def inverse_interpolate(start, end, value):def match_interpolate(new_start, new_end, old_start, old_end, old_value):return interpolate(- new_start, new_end,- inverse_interpolate(old_start, old_end, old_value)+ new_start, new_end, inverse_interpolate(old_start, old_end, old_value))@@ -116,6 +112,7 @@ def get_smooth_handle_points(points):def solve_func(b):return linalg.solve_banded((l, u), diag, b)+use_closed_solve_function = is_closed(points)if use_closed_solve_function:# Get equations to relate first and last points@@ -151,11 +148,10 @@ def diag_to_matrix(l_and_u, diag):matrix = np.zeros((dim, dim))for i in range(l + u + 1):np.fill_diagonal(- matrix[max(0, i - u):, max(0, u - i):],- diag[i, max(0, u - i):]+ matrix[max(0, i - u) :, max(0, u - i) :], diag[i, max(0, u - i) :])return matrixdef is_closed(points):- return np.allclose(points[0], points[-1])\ No newline at end of file+ return np.allclose(points[0], points[-1])diff --git a/manim/utils/color.py b/manim/utils/color.pyindex 5b06292e9..ebae3ddac 100644--- a/manim/utils/color.py+++ b/manim/utils/color.py@@ -35,17 +35,14 @@ def rgba_to_color(rgba):def rgb_to_hex(rgb):- return "#" + "".join('%02x' % int(255 * x) for x in rgb)+ return "#" + "".join("%02x" % int(255 * x) for x in rgb)def hex_to_rgb(hex_code):hex_part = hex_code[1:]if len(hex_part) == 3:"".join([2 * c for c in hex_part])- return np.array([- int(hex_part[i:i + 2], 16) / 255- for i in range(0, 6, 2)- ])+ return np.array([int(hex_part[i : i + 2], 16) / 255 for i in range(0, 6, 2)])def invert_color(color):@@ -53,7 +50,7 @@ def invert_color(color):def color_to_int_rgb(color):- return (255 * color_to_rgb(color)).astype('uint8')+ return (255 * color_to_rgb(color)).astype("uint8")def color_to_int_rgba(color, opacity=1.0):@@ -66,7 +63,7 @@ def color_gradient(reference_colors, length_of_output):return reference_colors[0]rgbs = list(map(color_to_rgb, reference_colors))alphas = np.linspace(0, (len(rgbs) - 1), length_of_output)- floors = alphas.astype('int')+ floors = alphas.astype("int")alphas_mod1 = alphas % 1# End edge casealphas_mod1[-1] = 1@@ -91,9 +88,7 @@ def average_color(*colors):def random_bright_color():color = random_color()curr_rgb = color_to_rgb(color)- new_rgb = interpolate(- curr_rgb, np.ones(len(curr_rgb)), 0.5- )+ new_rgb = interpolate(curr_rgb, np.ones(len(curr_rgb)), 0.5)return Color(rgb=new_rgb)@@ -103,7 +98,7 @@ def random_color():def get_shaded_rgb(rgb, point, unit_normal_vect, light_source):to_sun = normalize(light_source - point)- factor = 0.5 * np.dot(unit_normal_vect, to_sun)**3+ factor = 0.5 * np.dot(unit_normal_vect, to_sun) ** 3if factor < 0:factor *= 0.5result = rgb + factordiff --git a/manim/utils/config_ops.py b/manim/utils/config_ops.pyindex 6a3ca3a72..ebbf9b9b5 100644--- a/manim/utils/config_ops.py+++ b/manim/utils/config_ops.py@@ -77,18 +77,17 @@ def soft_dict_update(d1, d2):def digest_locals(obj, keys=None):- caller_locals = filtered_locals(- inspect.currentframe().f_back.f_locals- )+ caller_locals = filtered_locals(inspect.currentframe().f_back.f_locals)if keys is None:keys = list(caller_locals.keys())for key in keys:setattr(obj, key, caller_locals[key])+# 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(object):def __init__(self, dict):- self.__dict__ = dict\ No newline at end of file+ self.__dict__ = dictdiff --git a/manim/utils/debug.py b/manim/utils/debug.pyindex a1857ded0..e6bfec433 100644--- a/manim/utils/debug.py+++ b/manim/utils/debug.py@@ -18,4 +18,4 @@ def get_submobject_index_labels(mobject, label_height=0.15):label.move_to(submob)label.set_stroke(BLACK, 5, background=True)labels.add(label)- return labels\ No newline at end of file+ return labelsdiff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.pyindex 181cfb426..5459ee4ba 100644--- a/manim/utils/file_ops.py+++ b/manim/utils/file_ops.py@@ -4,7 +4,7 @@ import numpy as npdef add_extension_if_not_present(file_name, extension):# This could conceivably be smarter about handling existing differing extensions- if(file_name[-len(extension):] != extension):+ if file_name[-len(extension) :] != extension:return file_name + extensionelse:return file_name@@ -28,17 +28,18 @@ def seek_full_path_from_defaults(file_name, default_dir, extensions):raise IOError("File {} not Found".format(file_name))-def get_sorted_integer_files(directory,- min_index=0,- max_index=np.inf,- remove_non_integer_files=False,- remove_indices_greater_than=None,- extension=None,- ):+def get_sorted_integer_files(+ directory,+ min_index=0,+ max_index=np.inf,+ remove_non_integer_files=False,+ remove_indices_greater_than=None,+ extension=None,+):indexed_files = []for file in os.listdir(directory):- if '.' in file:- index_str = file[:file.index('.')]+ if "." in file:+ index_str = file[: file.index(".")]else:index_str = file@@ -56,4 +57,4 @@ def get_sorted_integer_files(directory,elif remove_non_integer_files:os.remove(full_path)indexed_files.sort(key=lambda p: p[0])- return list(map(lambda p: os.path.join(directory, p[1]), indexed_files))\ No newline at end of file+ return list(map(lambda p: os.path.join(directory, p[1]), indexed_files))diff --git a/manim/utils/images.py b/manim/utils/images.pyindex 1288e4fe7..6359d58d4 100644--- a/manim/utils/images.py+++ b/manim/utils/images.py@@ -10,7 +10,7 @@ def get_full_raster_image_path(image_file_name):return seek_full_path_from_defaults(image_file_name,default_dir=os.path.join("assets", "raster_images"),- extensions=[".jpg", ".png", ".gif"]+ extensions=[".jpg", ".png", ".gif"],)@@ -26,4 +26,4 @@ def drag_pixels(frames):def invert_image(image):arr = np.array(image)arr = (255 * np.ones(arr.shape)).astype(arr.dtype) - arr- return Image.fromarray(arr)\ No newline at end of file+ return Image.fromarray(arr)diff --git a/manim/utils/iterables.py b/manim/utils/iterables.pyindex 85ecc09e6..e8c99de01 100644--- a/manim/utils/iterables.py+++ b/manim/utils/iterables.py@@ -34,10 +34,7 @@ def all_elements_are_instances(iterable, Class):def adjacent_n_tuples(objects, n):- return zip(*[- [*objects[k:], *objects[:k]]- for k in range(n)- ])+ return zip(*[[*objects[k:], *objects[:k]] for k in range(n)])def adjacent_pairs(objects):@@ -56,9 +53,8 @@ def batch_by_property(items, property_func):def add_batch_prop_pair(batch):if len(batch) > 0:- batch_prop_pairs.append(- (batch, property_func(batch[0]))- )+ batch_prop_pairs.append((batch, property_func(batch[0])))+curr_batch = []curr_prop = Nonefor item in items:@@ -85,11 +81,10 @@ def tuplify(obj):def stretch_array_to_length(nparray, length):curr_len = len(nparray)if curr_len > length:- raise Warning(- "Trying to stretch array to a length shorter than its own")+ 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')]+ return nparray[indices.astype("int")]def make_even(iterable_1, iterable_2):@@ -97,7 +92,7 @@ def make_even(iterable_1, iterable_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)]+ [list_2[(n * len(list_2)) // length] for n in range(length)],)@@ -107,7 +102,7 @@ def make_even_by_cycling(iterable_1, iterable_2):cycle2 = it.cycle(iterable_2)return ([next(cycle1) for x in range(length)],- [next(cycle2) for x in range(length)]+ [next(cycle2) for x in range(length)],)@@ -119,4 +114,4 @@ def remove_nones(sequence):def concatenate_lists(*list_of_lists):- return [item for l in list_of_lists for item in l]\ No newline at end of file+ return [item for l in list_of_lists for item in l]diff --git a/manim/utils/paths.py b/manim/utils/paths.pyindex c630334e4..861e6095b 100644--- a/manim/utils/paths.py+++ b/manim/utils/paths.py@@ -36,6 +36,7 @@ def path_along_arc(arc_angle, axis=OUT):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@@ -44,4 +45,4 @@ def clockwise_path():def counterclockwise_path():- return path_along_arc(np.pi)\ No newline at end of file+ return path_along_arc(np.pi)diff --git a/manim/utils/rate_functions.py b/manim/utils/rate_functions.pyindex 184c9da1c..1dc0f4d78 100644--- a/manim/utils/rate_functions.py+++ b/manim/utils/rate_functions.py@@ -10,10 +10,7 @@ def linear(t):def smooth(t, inflection=10.0):error = sigmoid(-inflection / 2)- return np.clip(- (sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error),- 0, 1,- )+ return np.clip((sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error), 0, 1,)def rush_into(t, inflection=10.0):@@ -40,8 +37,8 @@ def there_and_back(t, inflection=10.0):return smooth(new_t, inflection)-def there_and_back_with_pause(t, pause_ratio=1. / 3):- a = 1. / pause_ratio+def there_and_back_with_pause(t, pause_ratio=1.0 / 3):+ a = 1.0 / pause_ratioif t < 0.5 - pause_ratio / 2:return smooth(a * t)elif t < 0.5 + pause_ratio / 2:@@ -57,6 +54,7 @@ def running_start(t, pull_factor=-0.5):def not_quite_there(func=smooth, proportion=0.7):def result(t):return proportion * func(t)+return result@@ -78,6 +76,7 @@ def squish_rate_func(func, a=0.4, b=0.6):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@@ -91,4 +90,4 @@ def lingering(t):def exponential_decay(t, half_life=0.1):# The half-life should be rather small to minimize# the cut-off error at the end- return 1 - np.exp(-t / half_life)\ No newline at end of file+ return 1 - np.exp(-t / half_life)diff --git a/manim/utils/simple_functions.py b/manim/utils/simple_functions.pyindex 5f8180554..20329e374 100644--- a/manim/utils/simple_functions.py+++ b/manim/utils/simple_functions.py@@ -38,6 +38,7 @@ def get_num_args(function):def get_parameters(function):return inspect.signature(function).parameters+# Just to have a less heavyweight name for this extremely common operation## We may wish to have more fine-grained control over division by zero behavior@@ -64,11 +65,7 @@ def fdiv(a, b, zero_over_zero_value=None):return np.true_divide(a, b, out=out, where=where)-def binary_search(function,- target,- lower_bound,- upper_bound,- tolerance=1e-4):+def binary_search(function, target, lower_bound, upper_bound, tolerance=1e-4):lh = lower_boundrh = upper_boundwhile abs(rh - lh) > tolerance:@@ -88,4 +85,4 @@ def binary_search(function,lh, rh = rh, lhelse:return None- return mh\ No newline at end of file+ return mhdiff --git a/manim/utils/sounds.py b/manim/utils/sounds.pyindex a5a6997bc..d98ffcf3d 100644--- a/manim/utils/sounds.py+++ b/manim/utils/sounds.py@@ -3,20 +3,11 @@ from ..utils.file_ops import seek_full_path_from_defaultsdef play_chord(*nums):- commands = [- "play",- "-n",- "-c1",- "--no-show-progress",- "synth",- ] + [- "sin %-" + str(num)- for num in nums- ] + [- "fade h 0.5 1 0.5",- ">",- os.devnull- ]+ commands = (+ ["play", "-n", "-c1", "--no-show-progress", "synth",]+ + ["sin %-" + str(num) for num in nums]+ + ["fade h 0.5 1 0.5", ">", os.devnull]+ )try:os.system(" ".join(commands))except:@@ -35,5 +26,5 @@ def get_full_sound_file_path(sound_file_name):return seek_full_path_from_defaults(sound_file_name,default_dir=os.path.join("assets", "sounds"),- extensions=[".wav", ".mp3"]- )\ No newline at end of file+ extensions=[".wav", ".mp3"],+ )diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.pyindex 1dc09de81..e56dfa3b0 100644--- a/manim/utils/space_ops.py+++ b/manim/utils/space_ops.py@@ -11,7 +11,7 @@ from ..utils.simple_functions import fdivdef get_norm(vect):- return sum([x**2 for x in vect])**0.5+ return sum([x ** 2 for x in vect]) ** 0.5# Quaternions@@ -21,26 +21,22 @@ def get_norm(vect):def quaternion_mult(q1, q2):w1, x1, y1, z1 = q1w2, x2, y2, z2 = q2- return np.array([- 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 np.array(+ [+ 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,+ ]+ )def quaternion_from_angle_axis(angle, axis):- return np.append(- np.cos(angle / 2),- np.sin(angle / 2) * normalize(axis)- )+ return np.append(np.cos(angle / 2), np.sin(angle / 2) * normalize(axis))def angle_axis_from_quaternion(quaternion):- axis = normalize(- quaternion[1:],- fall_back=np.array([1, 0, 0])- )+ axis = normalize(quaternion[1:], fall_back=np.array([1, 0, 0]))angle = 2 * np.arccos(quaternion[0])if angle > TAU / 2:angle = TAU - angle@@ -62,10 +58,7 @@ def rotate_vector(vector, angle, axis=OUT):# Use quaternions...because why notquat = quaternion_from_angle_axis(angle, axis)quat_inv = quaternion_conjugate(quat)- product = reduce(- quaternion_mult,- [quat, np.append(0, vector), quat_inv]- )+ product = reduce(quaternion_mult, [quat, np.append(0, vector), quat_inv])return product[1:]else:raise Exception("vector must be of dimension 2 or 3")@@ -74,7 +67,7 @@ def rotate_vector(vector, angle, axis=OUT):def thick_diagonal(dim, thickness=2):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')+ return (np.abs(row_indices - col_indices) < thickness).astype("uint8")def rotation_matrix(angle, axis):@@ -91,7 +84,7 @@ def rotation_about_z(angle):return [[np.cos(angle), -np.sin(angle), 0],[np.sin(angle), np.cos(angle), 0],- [0, 0, 1]+ [0, 0, 1],]@@ -113,19 +106,14 @@ def z_to_vector(vector):theta = -thetaelse:theta = 0- phi_down = np.array([- [np.cos(phi), 0, np.sin(phi)],- [0, 1, 0],- [-np.sin(phi), 0, np.cos(phi)]- ])+ phi_down = np.array(+ [[np.cos(phi), 0, np.sin(phi)], [0, 1, 0], [-np.sin(phi), 0, np.cos(phi)]]+ )return np.dot(rotation_about_z(theta), phi_down)def angle_between(v1, v2):- return np.arccos(np.dot(- v1 / get_norm(v1),- v2 / get_norm(v2)- ))+ return np.arccos(np.dot(v1 / get_norm(v1), v2 / get_norm(v2)))def angle_of_vector(vector):@@ -143,10 +131,7 @@ def angle_between_vectors(v1, v2):Returns the angle between two 3D vectors.This angle will always be btw 0 and pi"""- return np.arccos(fdiv(- np.dot(v1, v2),- get_norm(v1) * get_norm(v2)- ))+ return np.arccos(fdiv(np.dot(v1, v2), get_norm(v1) * get_norm(v2)))def project_along_vector(point, vector):@@ -166,11 +151,13 @@ def normalize(vect, fall_back=None):def cross(v1, v2):- return np.array([- v1[1] * v2[2] - v1[2] * v2[1],- v1[2] * v2[0] - v1[0] * v2[2],- v1[0] * v2[1] - v1[1] * v2[0]- ])+ return np.array(+ [+ v1[1] * v2[2] - v1[2] * v2[1],+ v1[2] * v2[0] - v1[0] * v2[2],+ v1[0] * v2[1] - v1[1] * v2[0],+ ]+ )def get_unit_normal(v1, v2):@@ -182,10 +169,7 @@ def get_unit_normal(v1, v2):def compass_directions(n=4, start_vect=RIGHT):angle = TAU / n- return np.array([- rotate_vector(start_vect, k * angle)- for k in range(n)- ])+ return np.array([rotate_vector(start_vect, k * angle) for k in range(n)])def complex_to_R3(complex_num):@@ -236,4 +220,4 @@ def get_winding_number(points):d_angle = angle_of_vector(p2) - angle_of_vector(p1)d_angle = ((d_angle + PI) % TAU) - PItotal_angle += d_angle- return total_angle / TAU\ No newline at end of file+ return total_angle / TAUdiff --git a/manim/utils/strings.py b/manim/utils/strings.pyindex caf07e558..e32b6120e 100644--- a/manim/utils/strings.py+++ b/manim/utils/strings.py@@ -4,17 +4,18 @@ import stringdef to_camel_case(name):- return "".join([- [c for c in part if c not in string.punctuation + string.whitespace].capitalize()- for part in name.split("_")- ])+ return "".join(+ [+ [+ c for c in part if c not in string.punctuation + string.whitespace+ ].capitalize()+ for part in name.split("_")+ ]+ )def initials(name, sep_values=[" ", "_"]):- return "".join([- (s[0] if s else "")- for s in re.split("|".join(sep_values), name)- ])+ return "".join([(s[0] if s else "") for s in re.split("|".join(sep_values), name)])def camel_case_initials(name):@@ -37,10 +38,16 @@ def split_string_to_isolate_substrings(full_string, *substrings_to_isolate):if len(substrings_to_isolate) == 0:return [full_string]substring_to_isolate = substrings_to_isolate[0]- all_substrings = list(it.chain(*list(zip(- full_string.split(substring_to_isolate),- it.repeat(substring_to_isolate)- ))))+ all_substrings = list(+ it.chain(+ *list(+ zip(+ full_string.split(substring_to_isolate),+ it.repeat(substring_to_isolate),+ )+ )+ )+ )all_substrings.pop(-1)all_substrings = [s for s in all_substrings if s != ""]return split_string_list_to_isolate_substrings(@@ -53,7 +60,11 @@ def split_string_list_to_isolate_substrings(string_list, *substrings_to_isolate)Similar to split_string_to_isolate_substrings, but the first argumentis a list of strings, thought of as something already broken up a bit."""- return list(it.chain(*[- split_string_to_isolate_substrings(s, *substrings_to_isolate)- for s in string_list- ]))\ No newline at end of file+ return list(+ it.chain(+ *[+ split_string_to_isolate_substrings(s, *substrings_to_isolate)+ for s in string_list+ ]+ )+ )diff --git a/manim/utils/tex.py b/manim/utils/tex.pyindex a38161b31..a3ec88af3 100644--- a/manim/utils/tex.py+++ b/manim/utils/tex.py@@ -1,13 +1,15 @@import osfrom ..utils.config_ops import digest_config-class TexTemplateFromFile():++class TexTemplateFromFile:"""Class representing a TeX template file""" # TODO: attributes, dataclasses stuff+CONFIG = {"use_ctex": False,- "filename" : "tex_template.tex",+ "filename": "tex_template.tex","text_to_replace": "YourTextHere",}body = ""@@ -23,7 +25,7 @@ class TexTemplateFromFile():with open(self.filename, "r") as infile:self.body = infile.read()- def get_text_for_text_mode(self,expression):+ def get_text_for_text_mode(self, expression):"""Inserting expression verbatim into TeX template.Parameters@@ -36,9 +38,7 @@ class TexTemplateFromFile()::class:`str`LaTeX code based on the template containing the given expression and ready for typesetting."""- return self.body.replace(- self.text_to_replace, expression- )+ return self.body.replace(self.text_to_replace, expression)def get_text_for_env(self, environment, expression):"""Inserts an expression into the TeX template, surrounded@@ -59,11 +59,10 @@ class TexTemplateFromFile():begin = r"\begin{" + environment + "}"end = r"\end{" + environment + "}"return self.body.replace(- self.text_to_replace,- "{0}\n{1}\n{2}".format(begin, expression, end)+ self.text_to_replace, "{0}\n{1}\n{2}".format(begin, expression, end))- def get_text_for_tex_mode(self,expression):+ def get_text_for_tex_mode(self, expression):"""Inserts an expression into the TeX template, surroundedby `\\begin{align*} ... \\end{align*}` for math mode.@@ -84,10 +83,11 @@ class TexTemplate(TexTemplateFromFile):"""Class for dynamically managing a TeX template""" # TODO: Add attributes (when dataclasses are implemented)+CONFIG = {- "documentclass": ["standalone",["preview"]],+ "documentclass": ["standalone", ["preview"]],"common_packages": [- ["babel",["english"]],+ ["babel", ["english"]],"amsmath","amssymb","dsfont",@@ -101,10 +101,10 @@ class TexTemplate(TexTemplateFromFile):"ragged2e","physics","xcolor",- "microtype"+ "microtype",],"tex_packages": [],- "ctex_packages": [["ctex",["UTF8"]]],+ "ctex_packages": [["ctex", ["UTF8"]]],"common_preamble_text": r"\linespread{1}" "\n","tex_preamble_text": r"\DisableLigatures{encoding = *, family = *}" "\n","ctex_preamble_text": "",@@ -120,7 +120,9 @@ class TexTemplate(TexTemplateFromFile):"""For faster access, the LaTeX template's code is cached.If the base file is modified, the cache needs to be rebuilt."""tpl = self.generate_tex_command(- "documentclass",required_params=[self.documentclass[0]], optional_params=self.documentclass[1]+ "documentclass",+ required_params=[self.documentclass[0]],+ optional_params=self.documentclass[1],)for pkg in self.common_packages:tpl += self.generate_usepackage(pkg)@@ -142,7 +144,7 @@ class TexTemplate(TexTemplateFromFile):tpl += f"\n{self.text_to_replace}\n"tpl += "\n" r"\end{document}"- self.body=tpl+ self.body = tpldef prepend_package(self, pkg):"""Adds a new package (or several new packages)@@ -170,7 +172,7 @@ class TexTemplate(TexTemplateFromFile):self.common_packages.append(pkg)self.rebuild_cache()- def append_to_preamble(self,text):+ def append_to_preamble(self, text):"""Adds commands (e.g. macro definitions) at the end of the preamble.Parameters@@ -194,7 +196,7 @@ class TexTemplate(TexTemplateFromFile):self.rebuild_cache()pass- def generate_tex_command(self,command, *, required_params, optional_params = []):+ def generate_tex_command(self, command, *, required_params, optional_params=[]):"""Function for creating LaTeX command strings with or without options.Internally used to generate `\\usepackage{...}`@@ -222,16 +224,18 @@ class TexTemplate(TexTemplateFromFile):return r"\{0}{1}{2}".format(command,f"[{','.join(optional_params)}]" if optional_params else "",- "".join("{" + param + "}" for param in required_params)+ "".join("{" + param + "}" for param in required_params),)- def generate_usepackage(self,pkg):- if isinstance(pkg,list):- return self.generate_tex_command("usepackage",required_params=[pkg[0]],optional_params=pkg[1])+ def generate_usepackage(self, pkg):+ if isinstance(pkg, list):+ return self.generate_tex_command(+ "usepackage", required_params=[pkg[0]], optional_params=pkg[1]+ )else:- return self.generate_tex_command("usepackage",required_params=[pkg])+ return self.generate_tex_command("usepackage", required_params=[pkg])- def get_text_for_text_mode(self,expression):+ def get_text_for_text_mode(self, expression):"""Inserts an expression verbatim into the TeX template.Parameters@@ -244,9 +248,7 @@ class TexTemplate(TexTemplateFromFile)::class:`str`LaTeX code based on the template, containing the given expression and ready for typesetting"""- return self.body.replace(- self.text_to_replace, expression- )+ return self.body.replace(self.text_to_replace, expression)def get_text_for_env(self, environment, expression):"""Inserts an expression into the TeX template, surrounded@@ -267,11 +269,10 @@ class TexTemplate(TexTemplateFromFile):begin = r"\begin{" + environment + "}"end = r"\end{" + environment + "}"return self.body.replace(- self.text_to_replace,- "{0}\n{1}\n{2}".format(begin, expression, end)+ self.text_to_replace, "{0}\n{1}\n{2}".format(begin, expression, end))- def get_text_for_tex_mode(self,expression):+ def get_text_for_tex_mode(self, expression):"""Inserts an expression into the TeX template, surroundedby `\\begin{align*} ... \\end{align*}` for math mode.diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.pyindex 7b574f380..b736c4f92 100644--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@ -16,7 +16,7 @@ def tex_hash(expression):def tex_to_svg_file(expression, source_type):- tex_template = config['tex_template']+ tex_template = config["tex_template"]tex_file = generate_tex_file(expression, tex_template, source_type)dvi_file = tex_to_dvi(tex_file, tex_template.use_ctex)return dvi_to_svg(dvi_file, use_ctex=tex_template.use_ctex)@@ -28,14 +28,9 @@ def generate_tex_file(expression, tex_template, source_type):elif source_type == "tex":output = tex_template.get_text_for_tex_mode(expression)- result = os.path.join(- file_writer_config['tex_dir'],- tex_hash(output)- ) + ".tex"+ result = os.path.join(file_writer_config["tex_dir"], tex_hash(output)) + ".tex"if not os.path.exists(result):- logger.info("Writing \"%s\" to %s" % (- "".join(expression), result- ))+ logger.info('Writing "%s" to %s' % ("".join(expression), result))with open(result, "w", encoding="utf-8") as outfile:outfile.write(output)return result@@ -45,34 +40,41 @@ def tex_to_dvi(tex_file, use_ctex=False):result = tex_file.replace(".tex", ".dvi" if not use_ctex else ".xdv")result = Path(result).as_posix()tex_file = Path(tex_file).as_posix()- tex_dir = Path(file_writer_config['tex_dir']).as_posix()+ tex_dir = Path(file_writer_config["tex_dir"]).as_posix()if not os.path.exists(result):- commands = [- "latex",- "-interaction=batchmode",- "-halt-on-error",- "-output-directory=\"{}\"".format(tex_dir),- "\"{}\"".format(tex_file),- ">",- os.devnull- ] if not use_ctex else [- "xelatex",- "-no-pdf",- "-interaction=batchmode",- "-halt-on-error",- "-output-directory=\"{}\"".format(tex_dir),- "\"{}\"".format(tex_file),- ">",- os.devnull- ]+ commands = (+ [+ "latex",+ "-interaction=batchmode",+ "-halt-on-error",+ '-output-directory="{}"'.format(tex_dir),+ '"{}"'.format(tex_file),+ ">",+ os.devnull,+ ]+ if not use_ctex+ else [+ "xelatex",+ "-no-pdf",+ "-interaction=batchmode",+ "-halt-on-error",+ '-output-directory="{}"'.format(tex_dir),+ '"{}"'.format(tex_file),+ ">",+ os.devnull,+ ]+ )exit_code = os.system(" ".join(commands))if exit_code != 0:log_file = tex_file.replace(".tex", ".log")raise Exception(- ("LaTeX error converting to dvi. "- if not use_ctex- else "XeLaTeX error converting to xdv. ") +- f"See log output above or the log file: {log_file}")+ (+ "LaTeX error converting to dvi. "+ if not use_ctex+ else "XeLaTeX error converting to xdv. "+ )+ + f"See log output above or the log file: {log_file}"+ )return result@@ -89,14 +91,14 @@ def dvi_to_svg(dvi_file, use_ctex=False, regen_if_exists=False):if not os.path.exists(result):commands = ["dvisvgm",- "\"{}\"".format(dvi_file),+ '"{}"'.format(dvi_file),"-n","-v","0","-o",- "\"{}\"".format(result),+ '"{}"'.format(result),">",- os.devnull+ os.devnull,]os.system(" ".join(commands))return resultdiff --git a/requirements.txt b/requirements.txtindex c18e38942..db5924cbf 100644--- a/requirements.txt+++ b/requirements.txt@@ -9,3 +9,4 @@ pygmentspyreadline; sys_platform == 'win32'rich# pytest (for development only)+# black (for development only)diff --git a/tests/conftest.py b/tests/conftest.pyindex c07ad705c..9d7a0128a 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -7,13 +7,16 @@ import loggingdef pytest_addoption(parser):- parser.addoption("--skip_end_to_end", action="store_true", default=False,- help="Will skip all the end-to-end tests. Useful when ffmpeg is not installed, e.g. on Windows jobs.")+ parser.addoption(+ "--skip_end_to_end",+ action="store_true",+ default=False,+ help="Will skip all the end-to-end tests. Useful when ffmpeg is not installed, e.g. on Windows jobs.",+ )def pytest_configure(config):- config.addinivalue_line(- "markers", "skip_end_to_end: mark test as end_to_end test")+ config.addinivalue_line("markers", "skip_end_to_end: mark test as end_to_end test")def pytest_collection_modifyitems(config, items):@@ -21,7 +24,8 @@ def pytest_collection_modifyitems(config, items):returnelse:skip_end_to_end = pytest.mark.skip(- reason="End to end test skipped due to --skip_end_to_end flag")+ reason="End to end test skipped due to --skip_end_to_end flag"+ )for item in items:if "skip_end_to_end" in item.keywords:item.add_marker(skip_end_to_end)diff --git a/tests/test_cli/test_cli.py b/tests/test_cli/test_cli.pyindex 0da7fa9bc..ab350c841 100644--- a/tests/test_cli/test_cli.py+++ b/tests/test_cli/test_cli.py@@ -4,12 +4,10 @@ from shutil import rmtreeimport pytest-def capture(command,instream=None):- proc = subprocess.Popen(command,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- stdin=instream- )+def capture(command, instream=None):+ proc = subprocess.Popen(+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=instream+ )out, err = proc.communicate()return out, err, proc.returncode@@ -17,41 +15,66 @@ def capture(command,instream=None):def test_help(python_version):command = [python_version, "-m", "manim", "--help"]out, err, exitcode = capture(command)- assert exitcode == 0, f"Manim has been installed incorrectly. Please refer to the troubleshooting section on the wiki. Error:\n{err.decode()}"+ assert (+ exitcode == 0+ ), f"Manim has been installed incorrectly. Please refer to the troubleshooting section on the wiki. Error:\n{err.decode()}"+def test_basicScene(python_version):""" Simulate SquareToCircle. The cache will be saved in tests_caches/media_temp (temporary directory). This is mainly intended to test the partial-movies process. """path_basic_scene = os.path.join("tests", "tests_data", "basic_scenes.py")path_output = os.path.join("tests_cache", "media_temp")- command = [python_version, "-m", "manim", path_basic_scene,- "SquareToCircle", "-l", "--media_dir", path_output]+ command = [+ python_version,+ "-m",+ "manim",+ path_basic_scene,+ "SquareToCircle",+ "-l",+ "--media_dir",+ path_output,+ ]out, err, exitcode = capture(command)assert exitcode == 0, err- assert os.path.exists(os.path.join(- path_output, "videos", "basic_scenes", "480p15", "SquareToCircle.mp4")), err+ assert os.path.exists(+ os.path.join(+ path_output, "videos", "basic_scenes", "480p15", "SquareToCircle.mp4"+ )+ ), errrmtree(path_output)+def test_WriteStuff(python_version):"""This is mainly intended to test the caching process of the tex objects"""path_basic_scene = os.path.join("tests", "tests_data", "basic_scenes.py")path_output = os.path.join("tests_cache", "media_temp")- command = [python_version, "-m", "manim", path_basic_scene,- "WriteStuff", "-l", "--media_dir", path_output]+ command = [+ python_version,+ "-m",+ "manim",+ path_basic_scene,+ "WriteStuff",+ "-l",+ "--media_dir",+ path_output,+ ]out, err, exitcode = capture(command)assert exitcode == 0, err- assert os.path.exists(os.path.join(- path_output, "videos", "basic_scenes", "480p15", "WriteStuff.mp4")), err+ assert os.path.exists(+ os.path.join(path_output, "videos", "basic_scenes", "480p15", "WriteStuff.mp4")+ ), errrmtree(path_output)+def test_dash_as_name(python_version):"""Simulate using - as a filename. Intended to test the feature that allows end users to type manim code on the spot."""path_output = os.path.join("tests_cache", "media_temp")command = [python_version, "-m", "manim", "-", "-l", "--media_dir", path_output]out, err, exitcode = capture(- command,- open(os.path.join(os.path.dirname(__file__), "dash_test_script.txt"))- )+ command, open(os.path.join(os.path.dirname(__file__), "dash_test_script.txt"))+ )assert exitcode == 0, err- assert os.path.exists(os.path.join(- path_output, "videos", "-", "480p15", "DashAsNameTest.mp4")), err+ assert os.path.exists(+ os.path.join(path_output, "videos", "-", "480p15", "DashAsNameTest.mp4")+ ), errrmtree(path_output)diff --git a/tests/test_creation.py b/tests/test_creation.pyindex 0745b2139..a20ef09b5 100644--- a/tests/test_creation.py+++ b/tests/test_creation.py@@ -23,6 +23,7 @@ class DrawBorderThenFillTest(Scene):# NOTE : Here should be the Write Test. But for some reasons it appears that this function is untestable (see issue #157)+class FadeOutTest(Scene):def construct(self):square = Square()@@ -89,5 +90,6 @@ class ShrinkToCenterTest(Scene):square = Square()self.play(ShrinkToCenter(square))+def test_scenes():utils_test_scenes(get_scenes_to_test(__name__), "creation")diff --git a/tests/test_geometry.py b/tests/test_geometry.pyindex 5e7a812a5..8ce9aa354 100644--- a/tests/test_geometry.py+++ b/tests/test_geometry.py@@ -89,8 +89,7 @@ class VectorTest(Scene):class PolygonTest(Scene):def construct(self):- a = Polygon(- *[np.array([1, 1, 0]), np.array([2, 2, 0]), np.array([2, 3, 0])])+ a = Polygon(*[np.array([1, 1, 0]), np.array([2, 2, 0]), np.array([2, 3, 0])])self.play(Animation(a))diff --git a/tests/test_graph.py b/tests/test_graph.pyindex a4783ef78..18306f87a 100644--- a/tests/test_graph.py+++ b/tests/test_graph.py@@ -11,15 +11,16 @@ class PlotFunctions(GraphScene):"graph_origin": ORIGIN,"function_color": RED,"axes_color": GREEN,- "x_labeled_nums": range(-10,12,2),+ "x_labeled_nums": range(-10, 12, 2),}def construct(self):constants.TEX_TEMPLATE = TexTemplate()self.setup_axes()- f = self.get_graph(lambda x: x**2)+ f = self.get_graph(lambda x: x ** 2)self.play(Animation(f))+def test_scenes():utils_test_scenes(get_scenes_to_test(__name__), "graph", caching_needed=True)diff --git a/tests/test_indication.py b/tests/test_indication.pyindex 48217c4f4..a780cd7ec 100644--- a/tests/test_indication.py+++ b/tests/test_indication.py@@ -73,5 +73,6 @@ class TurnInsideOutTest(Scene):self.add(square)self.play(TurnInsideOut(square))+def test_scenes():utils_test_scenes(get_scenes_to_test(__name__), "indication")diff --git a/tests/test_movements.py b/tests/test_movements.pyindex 1079a240a..87da4f448 100644--- a/tests/test_movements.py+++ b/tests/test_movements.py@@ -6,9 +6,10 @@ class HomotopyTest(Scene):def construct(self):def func(x, y, z, t):norm = get_norm([x, y])- tau = interpolate(5, -5, t) + norm/config['frame_x_radius']+ tau = interpolate(5, -5, t) + norm / config["frame_x_radius"]alpha = sigmoid(tau)- return [x, y + 0.5*np.sin(2*np.pi*alpha)-t*SMALL_BUFF/2, z]+ return [x, y + 0.5 * np.sin(2 * np.pi * alpha) - t * SMALL_BUFF / 2, z]+square = Square()self.play(Homotopy(func, square))@@ -16,8 +17,10 @@ class HomotopyTest(Scene):class PhaseFlowTest(Scene):def construct(self):square = Square()+def func(t):- return t*0.5*UP+ return t * 0.5 * UP+self.play(PhaseFlow(func, square))diff --git a/tests/test_threed.py b/tests/test_threed.pyindex 37fd406d8..87d85529c 100644--- a/tests/test_threed.py+++ b/tests/test_threed.py@@ -21,7 +21,7 @@ class CameraMoveTest(ThreeDScene):def construct(self):cube = Cube()self.play(Animation(cube))- self.move_camera(phi=PI/4, theta=PI/4)+ self.move_camera(phi=PI / 4, theta=PI / 4)class AmbientCameraMoveTest(ThreeDScene):diff --git a/tests/test_transform.py b/tests/test_transform.pyindex 85ad38232..80f83dfb3 100644--- a/tests/test_transform.py+++ b/tests/test_transform.py@@ -34,18 +34,18 @@ class MoveToTargetTest(Scene):def construct(self):square = Square()square.generate_target()- square.target.shift(3*UP)+ square.target.shift(3 * UP)self.play(MoveToTarget(square))class ApplyPointwiseFunctionTest(Scene):def construct(self):square = Square()+def func(p):return np.array([1.0, 1.0, 0.0])- self.play(- ApplyPointwiseFunction(func, square)- )++ self.play(ApplyPointwiseFunction(func, square))class FadeToColortTest(Scene):@@ -80,18 +80,15 @@ class ApplyFunctionTest(Scene):def construct(self):square = Square()self.add(square)+def apply_function(mob):mob.scale(2)mob.to_corner(UR)- mob.rotate(PI/4)+ mob.rotate(PI / 4)mob.set_color(RED)return mob- self.play(- ApplyFunction(- apply_function,- square- )- )++ self.play(ApplyFunction(apply_function, square))class ApplyComplexFunctionTest(Scene):diff --git a/tests/test_updaters.py b/tests/test_updaters.pyindex 773298972..c3bd80177 100644--- a/tests/test_updaters.py+++ b/tests/test_updaters.py@@ -9,15 +9,15 @@ class UpdaterTest(Scene):self.add(dot, square)square.add_updater(lambda m: m.next_to(dot, RIGHT, buff=SMALL_BUFF))self.add(square)- self.play(dot.shift, UP*2)+ self.play(dot.shift, UP * 2)square.clear_updaters()class ValueTrackerTest(Scene):def construct(self):- theta = ValueTracker(PI/2)- line_1 = Line(ORIGIN, RIGHT*3, color=RED)- line_2 = Line(ORIGIN, RIGHT*3, color=GREEN)+ theta = ValueTracker(PI / 2)+ line_1 = Line(ORIGIN, RIGHT * 3, color=RED)+ line_2 = Line(ORIGIN, RIGHT * 3, color=GREEN)line_2.rotate(theta.get_value(), about_point=ORIGIN)diff --git a/tests/test_writing.py b/tests/test_writing.pyindex 6a2a6869d..5f9b9de57 100644--- a/tests/test_writing.py+++ b/tests/test_writing.py@@ -2,35 +2,32 @@ from manim import *from testing_utils import utils_test_scenes, get_scenes_to_test-#NOTE : All of these tests use cached data (in /test_cache)+# NOTE : All of these tests use cached data (in /test_cache)# Cache functionality is tested within test_CLI.+class TextTest(Scene):def construct(self):- t = Text('testing', font = "Arial")+ t = Text("testing", font="Arial")self.play(Animation(t))class TextMobjectTest(Scene):def construct(self):constants.TEX_TEMPLATE = TexTemplate()- t = TextMobject('Hello world !')+ t = TextMobject("Hello world !")self.play(Animation(t))class TexMobjectTest(Scene):def construct(self):- #IMPORTANT NOTE : This won't test the abitilty of manim to write/cache latex.+ # IMPORTANT NOTE : This won't test the abitilty of manim to write/cache latex.# i.e It will pass even if latex is not installed.# This is due to the fact that the latex used here has been cached (see test_cache directory)constants.TEX_TEMPLATE = TexTemplate()- t = TexMobject(- "\\sum_{n=1}^\\infty "- "\\frac{1}{n^2} = \\frac{\\pi^2}{6}"- )+ t = TexMobject("\\sum_{n=1}^\\infty " "\\frac{1}{n^2} = \\frac{\\pi^2}{6}")self.play(Animation(t))-def test_scenes():utils_test_scenes(get_scenes_to_test(__name__), "writing", caching_needed=True)diff --git a/tests/testing_utils.py b/tests/testing_utils.pyindex cf6d96bd7..f2d1522b9 100644--- a/tests/testing_utils.py+++ b/tests/testing_utils.py@@ -34,19 +34,23 @@ class SceneTester:def __init__(self, scene_object, module_tested, caching_needed=False):# Disable the the logs, (--quiet is broken) TODOlogging.disable(logging.CRITICAL)- self.path_tests_medias_cache = os.path.join('tests', 'tests_cache', module_tested)- self.path_tests_data = os.path.join('tests', 'tests_data', module_tested)+ self.path_tests_medias_cache = os.path.join(+ "tests", "tests_cache", module_tested+ )+ self.path_tests_data = os.path.join("tests", "tests_data", module_tested)if caching_needed:- file_writer_config['text_dir'] = os.path.join(- self.path_tests_medias_cache, scene_object.__name__, 'Text')- file_writer_config['tex_dir'] = os.path.join(- self.path_tests_medias_cache, scene_object.__name__, 'Tex')-- file_writer_config['skip_animations'] = True- config['pixel_height'] = 480- config['pixel_width'] = 854- config['frame_rate'] = 15+ file_writer_config["text_dir"] = os.path.join(+ self.path_tests_medias_cache, scene_object.__name__, "Text"+ )+ file_writer_config["tex_dir"] = os.path.join(+ self.path_tests_medias_cache, scene_object.__name__, "Tex"+ )++ file_writer_config["skip_animations"] = True+ config["pixel_height"] = 480+ config["pixel_width"] = 854+ config["frame_rate"] = 15# By invoking this, the scene is rendered.self.scene = scene_object()@@ -60,19 +64,20 @@ class SceneTester:The pre-rendered frame."""frame_data_path = os.path.join(- self.path_tests_data, "{}.npy".format(str(self.scene)))+ self.path_tests_data, "{}.npy".format(str(self.scene))+ )return np.load(frame_data_path)-def test(self):"""Compare pre-rendered frame to the frame rendered during the test."""frame_data = self.scene.get_frame()expected_frame_data = self.load_data()- assert frame_data.shape == expected_frame_data.shape, \- "The frames have different shape:" \- + f"\nexpected_frame_data.shape = {expected_frame_data.shape}" \+ assert frame_data.shape == expected_frame_data.shape, (+ "The frames have different shape:"+ + f"\nexpected_frame_data.shape = {expected_frame_data.shape}"+ f"\nframe_data.shape = {frame_data.shape}"+ )test_result = np.array_equal(frame_data, expected_frame_data)if not test_result:@@ -80,10 +85,11 @@ class SceneTester:first_incorrect_index = incorrect_indices[0][:2]first_incorrect_point = frame_data[tuple(first_incorrect_index)]expected_point = expected_frame_data[tuple(first_incorrect_index)]- assert test_result, \- f"The frames don't match. {str(self.scene).replace('Test', '')} has been modified." \- + "\nPlease ignore if it was intended." \+ assert test_result, (+ f"The frames don't match. {str(self.scene).replace('Test', '')} has been modified."+ + "\nPlease ignore if it was intended."+ f"\nFirst unmatched index is at {first_incorrect_index}: {first_incorrect_point} != {expected_point}"+ )def get_scenes_to_test(module_name):@@ -99,13 +105,15 @@ def get_scenes_to_test(module_name)::class:`list`The list of all the classes of the module."""- return inspect.getmembers(sys.modules[module_name], lambda m: inspect.isclass(m) and m.__module__ == module_name)+ return inspect.getmembers(+ sys.modules[module_name],+ lambda m: inspect.isclass(m) and m.__module__ == module_name,+ )def utils_test_scenes(scenes_to_test, module_name, caching_needed=False):for _, scene_tested in scenes_to_test:- SceneTester(scene_tested, module_name,- caching_needed=caching_needed).test()+ SceneTester(scene_tested, module_name, caching_needed=caching_needed).test()def set_test_scene(scene_object, module_name):@@ -125,16 +133,15 @@ def set_test_scene(scene_object, module_name):Normal usage::set_test_scene(DotTest, "geometry")"""- file_writer_config['skip_animations'] = True- config['pixel_height'] = 480- config['pixel_width'] = 854- config['frame_rate'] = 15+ file_writer_config["skip_animations"] = True+ config["pixel_height"] = 480+ config["pixel_width"] = 854+ config["frame_rate"] = 15scene = scene_object()data = scene.get_frame()- path = os.path.join("manim", "tests", "tests_data",- "{}".format(module_name))+ path = os.path.join("manim", "tests", "tests_data", "{}".format(module_name))if not os.path.isdir(path):os.makedirs(path)np.save(os.path.join(path, str(scene)), data)- logger.info('Test data saved in ' + path + '\n')+ logger.info("Test data saved in " + path + "\n")diff --git a/tests/tests_data/basic_scenes.py b/tests/tests_data/basic_scenes.pyindex cc57e0d67..5d1ffff5b 100644--- a/tests/tests_data/basic_scenes.py+++ b/tests/tests_data/basic_scenes.py@@ -2,6 +2,7 @@ from manim import *# This module is used in the CLI tests in tests_CLi.py.+class SquareToCircle(Scene):def construct(self):circle = Circle()@@ -14,17 +15,17 @@ class SquareToCircle(Scene):self.play(Transform(square, circle))self.play(FadeOut(square))+class WriteStuff(Scene):def construct(self):example_text = TextMobject(- "This is a some text",- tex_to_color_map={"text": YELLOW}+ "This is a some text", tex_to_color_map={"text": YELLOW})example_tex = TexMobject("\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}",)group = VGroup(example_text, example_tex)group.arrange(DOWN)- group.set_width(config['frame_width'] - 2 * LARGE_BUFF)+ group.set_width(config["frame_width"] - 2 * LARGE_BUFF)self.play(Write(example_text))