A community-maintained Python framework for creating mathematical animations.
Refactored scene caching and fixed issue when a different hash was produced when copying a mobject in the scene (#1211)
Hugues Devimeuxf6d63d78e9c3
diff --git a/manim/utils/hashing.py b/manim/utils/hashing.pyindex 39c84712f..02b808636 100644--- a/manim/utils/hashing.py+++ b/manim/utils/hashing.py@@ -1,20 +1,140 @@"""Utilities for scene caching."""+import collectionsimport copyimport inspectimport json+import typingimport zlibfrom time import perf_counterfrom types import FunctionType, MappingProxyType, MethodType, ModuleType+from typing import Anyimport numpy as npfrom .. import logger-ALREADY_PROCESSED_ID = {}+# Sometimes there are elements that are not suitable for hashing (too long or run-dependent)+# This is used to filter them out.+KEYS_TO_FILTER_OUT = set(+ ["original_id", "background", "pixel_array", "pixel_array_to_cairo_context"]+)-class CustomEncoder(json.JSONEncoder):+class _Memoizer:+ """Implements the memoization logic to optimize the hashing procedure and prevent the circular references within iterable processed.++ Keeps a record of all the processed objects, and handle the logic to return a place holder instead of the original object if the object has already been processed+ by the hashing logic (i.e, recursively checked, converted to JSON, etc..).++ This class uses two signatures functions to keep a track of processed objects : hash or id. Whenever possible, hash is used to ensure a broader object content-equality detection.+ """++ _already_processed = set()++ # Can be changed to whatever string to help debugging the JSon generation.+ ALREADY_PROCESSED_PLACEHOLDER = "ALREADY PROCESSED"++ @classmethod+ def reset_already_processed(cls):+ cls._already_processed.clear()++ @classmethod+ def check_already_processed_decorator(cls: "_Memoizer", is_method=False):+ """Decorator to handle the arguments that goes through the decorated function. Returns _ALREADY_PROCESSED_PLACEHOLDER if the obj has been processed, or lets the decorated function call go ahead.++ Parameters+ ----------+ is_method : bool, optional+ Whether the function passed is a method, by default False.+ """++ def layer(func):+ # NOTE : There is probably a better way to separate both case when func is a method or a function.+ if is_method:+ return lambda self, obj: cls._handle_already_processed(+ obj, default_function=lambda obj: func(self, obj)+ )+ return lambda obj: cls._handle_already_processed(obj, default_function=func)++ return layer++ @classmethod+ def check_already_processed(cls, obj: Any) -> Any:+ """Checks if obj has been already processed. Returns itself if it has not been, or the value of _ALREADY_PROCESSED_PLACEHOLDER if it has.+ Marks the object as processed in the second case.++ Parameters+ ----------+ obj : Any+ The object to check.++ Returns+ -------+ Any+ Either the object itself or the placeholder.+ """+ # When the object is not memoized, we return the object itself.+ return cls._handle_already_processed(obj, lambda x: x)++ @classmethod+ def mark_as_processed(cls, obj: Any) -> None:+ """Marks an object as processed.++ Parameters+ ----------+ obj : Any+ The object to mark as processed.+ """+ cls._handle_already_processed(obj, lambda x: x)+ return cls._return(obj, id, lambda x: x, memoizing=False)++ @classmethod+ def _handle_already_processed(+ cls, obj, default_function: typing.Callable[[Any], Any]+ ):+ if (+ isinstance(+ obj,+ (+ int,+ float,+ str,+ complex,+ ),+ )+ and obj not in [None, cls.ALREADY_PROCESSED_PLACEHOLDER]+ ):+ # It makes no sense (and it'd slower) to memoize objects of these primitive types.+ # Hence, we simply return the object.+ return obj+ if isinstance(obj, collections.abc.Hashable):+ try:+ return cls._return(obj, hash, default_function)+ except TypeError:+ # In case of an error with the hash (eg an object is marked as hashable but contains a non hashable within it)+ # Fallback to use the built-in function id instead.+ pass+ return cls._return(obj, id, default_function)++ @classmethod+ def _return(+ cls,+ obj: typing.Any,+ obj_to_membership_sign: typing.Callable[[Any], int],+ default_func,+ memoizing=True,+ ) -> typing.Union[str, Any]:++ obj_membership_sign = obj_to_membership_sign(obj)+ if obj_membership_sign in cls._already_processed:+ return cls.ALREADY_PROCESSED_PLACEHOLDER+ if memoizing:+ cls._already_processed.add(obj_membership_sign)+ return default_func(obj)+++class _CustomEncoder(json.JSONEncoder):def default(self, obj):"""This method is used to serialize objects to JSON format.@@ -52,7 +172,7 @@ class CustomEncoder(json.JSONEncoder):# hash collision (due to the same, empty, code strings) at some point.# See https://github.com/ManimCommunity/manim/pull/402.code = ""- return self._check_iterable({"code": code, "nonlocals": cvardict})+ return self._cleaned_iterable({"code": code, "nonlocals": cvardict})elif isinstance(obj, np.ndarray):if obj.size > 1000:obj = np.resize(obj, (100, 100))@@ -65,35 +185,12 @@ class CustomEncoder(json.JSONEncoder):# Indeed, there is certainly no case where scene-caching will receive only a non instancied object, as this is never used in the library or encouraged to be used user-side.if isinstance(temp, MappingProxyType):return "MappingProxy"- return self._check_iterable(temp)+ return self._cleaned_iterable(temp)elif isinstance(obj, np.uint8):return int(obj)-return f"Unsupported type for serializing -> {str(type(obj))}"- def _handle_already_processed(self, obj):- """Handle if an object has been already processed by checking the id of the object.-- This prevents the mechanism to handle an object several times, and is used to prevent any circular reference.-- Parameters- ----------- obj : Any- The obj to check.-- Returns- -------- Any- "already_processed" string if it has been processed, otherwise obj.- """- global ALREADY_PROCESSED_ID- if id(obj) in ALREADY_PROCESSED_ID:- return "already_processed"- if not isinstance(obj, (str, int, bool, float)):- ALREADY_PROCESSED_ID[id(obj)] = obj- return obj-- def _check_iterable(self, iterable):+ def _cleaned_iterable(self, iterable):"""Check for circular reference at each iterable that will go through the JSONEncoder, as well as key of the wrong format.If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here.@@ -106,47 +203,40 @@ class CustomEncoder(json.JSONEncoder):"""def _key_to_hash(key):- return zlib.crc32(json.dumps(key, cls=CustomEncoder).encode())+ return zlib.crc32(json.dumps(key, cls=_CustomEncoder).encode())def _iter_check_list(lst):- # We have to make a copy, as we don't want to touch to the original list- # A deepcopy isn't necessary as it is already recursive.- lst_copy = copy.copy(lst)- if isinstance(lst, tuple):- # NOTE: Sometimes a tuple can pass through this function. As a tuple- # is immutable, we convert it to a list to be able to modify it.- # It's ok as it is a copy.- lst_copy = list(lst_copy)+ processed_list = [None] * len(lst)for i, el in enumerate(lst):- if not isinstance(lst, tuple):- lst_copy[i] = self._handle_already_processed(- el- ) # ISSUE here, because of copy.+ el = _Memoizer.check_already_processed(el)if isinstance(el, (list, tuple)):- lst_copy[i] = _iter_check_list(el)+ new_value = _iter_check_list(el)elif isinstance(el, dict):- lst_copy[i] = _iter_check_dict(el)- return lst_copy+ new_value = _iter_check_dict(el)+ else:+ new_value = el+ processed_list[i] = new_value+ return processed_listdef _iter_check_dict(dct):- # We have to make a copy, as we don't want to touch to the original dict- # A deepcopy isn't necessary as it is already recursive.- dct_copy = copy.copy(dct)+ processed_dict = {}for k, v in dct.items():- dct_copy[k] = self._handle_already_processed(v)+ v = _Memoizer.check_already_processed(v)+ if k in KEYS_TO_FILTER_OUT:+ continue# We check if the k is of the right format (supporter by Json)if not isinstance(k, (str, int, float, bool)) and k is not None:k_new = _key_to_hash(k)- # We delete the value coupled with the old key, as the value is now coupled with the new key.- dct_copy[k_new] = dct_copy[k]- del dct_copy[k]else:k_new = kif isinstance(v, dict):- dct_copy[k_new] = _iter_check_dict(v)+ new_value = _iter_check_dict(v)elif isinstance(v, (list, tuple)):- dct_copy[k_new] = _iter_check_list(v)- return dct_copy+ new_value = _iter_check_list(v)+ else:+ new_value = v+ processed_dict[k_new] = new_value+ return processed_dictif isinstance(iterable, (list, tuple)):return _iter_check_list(iterable)@@ -166,12 +256,9 @@ class CustomEncoder(json.JSONEncoder)::class:`str`The object encoder with the standard json process."""- # We need to mark as already processed the first object to go in the process,- # As after, only objects that come from iterables will be marked as such.- global ALREADY_PROCESSED_ID- ALREADY_PROCESSED_ID[id(obj)] = obj+ _Memoizer.mark_as_processed(obj)if isinstance(obj, (dict, list, tuple)):- return super().encode(self._check_iterable(obj))+ return super().encode(self._cleaned_iterable(obj))return super().encode(obj)@@ -188,34 +275,12 @@ def get_json(obj)::class:`str`The flattened object"""- return json.dumps(obj, cls=CustomEncoder)---def get_camera_dict_for_hashing(camera_object):- """Remove some keys from `camera_object.__dict__` that are very heavy and useless for the caching functionality.-- Parameters- ----------- camera_object : :class:`~.Camera`- The camera object used in the scene-- Returns- -------- :class:`dict`- `Camera.__dict__` but cleaned.- """- camera_object_dict = copy.copy(camera_object.__dict__)- # We have to clean a little bit of camera_dict, as pixel_array and background are two very big numpy arrays. They- # are not essential to caching process. We also have to remove pixel_array_to_cairo_context as it contains used- # memory address (set randomly). See l.516 get_cached_cairo_context in camera.py- for to_clean in ["background", "pixel_array", "pixel_array_to_cairo_context"]:- camera_object_dict.pop(to_clean, None)- return camera_object_dict+ return json.dumps(obj, cls=_CustomEncoder)def get_hash_from_play_call(scene_object, camera_object, animations_list, current_mobjects_list-):+) -> str:"""Take the list of animations and a list of mobjects and output their hashes. This is meant to be used for `scene.play` function.Parameters@@ -238,75 +303,19 @@ def get_hash_from_play_call(A string concatenation of the respective hashes of `camera_object`, `animations_list` and `current_mobjects_list`, separated by `_`."""logger.debug("Hashing ...")- global ALREADY_PROCESSED_ID- # We add the scene object within the ALREADY_PROCESSED_ID, as we don't want to process because pretty much all of its attributes will be soon or later processed (in one of the three hashes).- ALREADY_PROCESSED_ID = {id(scene_object): scene_object}t_start = perf_counter()- camera_json = get_json(get_camera_dict_for_hashing(camera_object))+ _Memoizer.mark_as_processed(scene_object)+ camera_json = get_json(camera_object)animations_list_json = [get_json(x) for x in sorted(animations_list, key=str)]current_mobjects_list_json = [get_json(x) for x in current_mobjects_list]hash_camera, hash_animations, hash_current_mobjects = [zlib.crc32(repr(json_val).encode())for json_val in [camera_json, animations_list_json, current_mobjects_list_json]]- t_end = perf_counter()- logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})hash_complete = f"{hash_camera}_{hash_animations}_{hash_current_mobjects}"- # This will reset ALREADY_PROCESSED_ID as all the hashing process is finished.- ALREADY_PROCESSED_ID = {}- logger.debug("Hash generated : %(h)s", {"h": hash_complete})- return hash_complete---def get_hash_from_wait_call(- scene_object,- camera_object,- wait_time,- stop_condition_function,- current_mobjects_list,-):- """Take a wait time, a boolean function as a stop condition and a list of mobjects, and then output their individual hashes. This is meant to be used for `scene.wait` function.-- Parameters- ------------ scene_object : :class:`~.Scene`- The scene object.- camera_object : :class:`~.Camera`- The camera object.- wait_time : :class:`float`- The time to wait- stop_condition_function : Callable[[...], bool]- Boolean function used as a stop_condition in `wait`.-- Returns- -------- :class:`str`- A concatenation of the respective hashes of `animations_list and `current_mobjects_list`, separated by `_`.- """- logger.debug("Hashing ...")- t_start = perf_counter()- global ALREADY_PROCESSED_ID- # We add the scene object within the ALREADY_PROCESSED_ID, as we don't want to process because pretty much all of its attributes will be soon or later processed (in one of the three hashes).- ALREADY_PROCESSED_ID = {id(scene_object): scene_object}- camera_json = get_json(get_camera_dict_for_hashing(camera_object))- current_mobjects_list_json = [get_json(x) for x in current_mobjects_list]- hash_current_mobjects = zlib.crc32(repr(current_mobjects_list_json).encode())- hash_camera = zlib.crc32(repr(camera_json).encode())- if stop_condition_function is not None:- hash_function = zlib.crc32(get_json(stop_condition_function).encode())- # This will reset ALREADY_PROCESSED_ID as all the hashing process is finished.- ALREADY_PROCESSED_ID = {}- t_end = perf_counter()- logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})- hash_complete = f"{hash_camera}_{str(wait_time).replace('.', '-')}{hash_function}_{hash_current_mobjects}"- logger.debug("Hash generated : %(h)s", {"h": hash_complete})- return hash_complete- ALREADY_PROCESSED_ID = {}t_end = perf_counter()logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})- hash_complete = (- f"{hash_camera}_{str(wait_time).replace('.', '-')}_{hash_current_mobjects}"- )-+ # End of the hashing for the animation, reset all the memoize.+ _Memoizer.reset_already_processed()logger.debug("Hash generated : %(h)s", {"h": hash_complete})return hash_completediff --git a/tests/test_hashing.py b/tests/test_hashing.pyindex 1200fda6d..b713dcc5f 100644--- a/tests/test_hashing.py+++ b/tests/test_hashing.py@@ -1,6 +1,17 @@import json+from zlib import crc32++import pytestimport manim.utils.hashing as hashing+from manim import Square++ALREADY_PROCESSED_PLACEHOLDER = hashing._Memoizer.ALREADY_PROCESSED_PLACEHOLDER++[email protected](autouse=True, scope="function")+def reset_already_processed():+ hashing._Memoizer.reset_already_processed()def test_JSON_basic():@@ -81,8 +92,7 @@ def test_JSON_with_wrong_keys():a = {(1, 2): 3}b = {Test(): 3}c = {test: 3}-- for el in (a, b, c):+ for el in [a, b, c]:o_ser = hashing.get_json(el)dict_o = json.loads(o_ser)# check if this is an int (it meant that the lkey has been hashed)@@ -99,7 +109,7 @@ def test_JSON_with_circular_references():B["circular_ref"] = A()o_ser = hashing.get_json(B)dict_o = json.loads(o_ser)- assert dict_o["circular_ref"]["b"]["circular_ref"] == "already_processed"+ assert dict_o["circular_ref"]["b"] == ALREADY_PROCESSED_PLACEHOLDERdef test_JSON_with_big_np_array():@@ -114,3 +124,36 @@ def test_JSON_with_tuple():o = [(1, [1])]o_ser = hashing.get_json(o)assert o_ser == "[[1, [1]]]"+++def test_JSON_with_object_that_is_itself_circular_reference():+ class T:+ def __init__(self) -> None:+ self.a = None++ o = T()+ o.a = o+ hashing.get_json(o)+++def test_hash_consistency():+ def assert_two_objects_produce_same_hash(obj1, obj2, debug=False):+ """+ When debug is True, if the hashes differ an assertion comparing (element-wise) the two objects will be raised,+ and pytest will display a nice difference summary making it easier to debug.+ """+ json1 = hashing.get_json(obj1)+ hashing._Memoizer.reset_already_processed()+ json2 = hashing.get_json(obj2)+ hashing._Memoizer.reset_already_processed()+ hash1 = crc32(repr(json1).encode())+ hash2 = crc32(repr(json2).encode())+ if hash1 != hash2 and debug:+ dict1 = json.loads(json1)+ dict2 = json.loads(json2)+ assert dict1 == dict2+ assert hash1 == hash2, f"{obj1} and {obj2} have different hashes."++ assert_two_objects_produce_same_hash(Square(), Square())+ s = Square()+ assert_two_objects_produce_same_hash(s, s.copy())diff --git a/tests/test_scene_rendering/test_cairo_renderer.py b/tests/test_scene_rendering/test_cairo_renderer.pyindex 9e098cdf1..7e1f355d9 100644--- a/tests/test_scene_rendering/test_cairo_renderer.py+++ b/tests/test_scene_rendering/test_cairo_renderer.py@@ -36,18 +36,23 @@ def test_skipping_status_with_from_to_and_up_to(using_temp_config, disabling_cacdef test_when_animation_is_cached(using_temp_config):- scene = SquareToCircle()- # Render twice to create a cache.- scene.render()- pmf = scene.renderer.file_writer.partial_movie_files+ partial_movie_files = []+ for _ in range(2):+ # Render several times to generate a cache.+ # In some edgy cases and on some OS, a same scene can produce+ # a (finite, generally 2) number of different hash. In this case, the scene wouldn't be detected as cached, making the test fail.+ scene = SquareToCircle()+ scene.render()+ partial_movie_files.append(scene.renderer.file_writer.partial_movie_files)scene = SquareToCircle()scene.update_to_time = Mock()scene.render()assert scene.renderer.file_writer.is_already_cached(scene.renderer.animations_hashes[0])- # Check that the same partial movie files has been used (with the same hash)- assert pmf == scene.renderer.file_writer.partial_movie_files+ # Check that the same partial movie files has been used (with he same hash).+ # As there might have been several hashes, a list is used.+ assert scene.renderer.file_writer.partial_movie_files in partial_movie_files# Check that manim correctly skipped the animation.scene.update_to_time.assert_called_once_with(1)# Check that the output video has been generated.