Coverage for src/manimgx/animation/matching.py: 97%

78 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1# SPDX-FileCopyrightText: 2026 Academa, Inc. 

2# SPDX-FileCopyrightText: 2024 the Manim Community Developers 

3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC 

4# SPDX-License-Identifier: MIT 

5 

6"""Ported from Manim CE 0.21 (MIT).""" 

7 

8from __future__ import annotations 

9 

10from warnings import deprecated 

11 

12__all__ = [ 

13 "TransformMatchingAbstractBase", 

14 "TransformMatchingShapes", 

15 "TransformMatchingTex", 

16] 

17from collections.abc import Hashable, Mapping 

18from typing import TYPE_CHECKING, Unpack 

19 

20import numpy as np 

21 

22from manimgx.animation.motion import FadeIn, FadeOut, FadeTransformPieces 

23from manimgx.animation.transform import Transform, TransformOptions 

24from manimgx.mobject import Group, Mobject 

25from manimgx.mobjects.text import MathTexPart 

26 

27from .timeline import AnimationGroup 

28 

29if TYPE_CHECKING: 

30 from manimgx.scene import Scene 

31 

32 

33@deprecated( 

34 "the base of TransformMatchingShapes and TransformMatchingTex: use either", 

35 category=None, 

36) 

37class TransformMatchingAbstractBase(AnimationGroup): 

38 """The base of the transforms that match the parts of two mobjects: the parts that 

39 match move to their counterparts, and the others fade. 

40 

41 Each part of `mobject` and of `target_mobject` has a key 

42 ([`get_mobject_key`][manimgx.TransformMatchingAbstractBase.get_mobject_key]). The 

43 parts of `mobject` whose key a part of the target has transform into the target's 

44 parts with that key; the others fade out, moving to where the target's unmatched 

45 parts are, as those fade in in their places (unless `transform_mismatches` or 

46 `fade_transform_mismatches` has them transform). Parts are matched in their own 

47 order, so the result is the same in every run. When the animation finishes, 

48 `target_mobject` is in the scene in the place of `mobject`, which is left out of it 

49 as it was. A subclass says what the parts are 

50 ([`get_mobject_parts`][manimgx.TransformMatchingAbstractBase.get_mobject_parts]) and 

51 what their keys are. 

52 

53 Args: 

54 mobject: The mobject to transform. 

55 target_mobject: The mobject it becomes. 

56 transform_mismatches: Whether the unmatched parts transform into the target's 

57 unmatched parts, rather than fade. 

58 fade_transform_mismatches: Whether they cross-fade into the target's unmatched 

59 parts (see [`FadeTransformPieces`][manimgx.FadeTransformPieces]), rather 

60 than fade. 

61 key_map: Pairs of keys to match although they differ: the parts of `mobject` 

62 with the first key cross-fade into the target's parts with the second. 

63 These matches take precedence over equal keys. 

64 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

65 each of the animations it plays. 

66 """ 

67 

68 # the parts are matched in their own order, so the result is the same in every run 

69 # (CE matched through salted hashes, in set order) 

70 

71 def __init__[Key: Hashable]( 

72 self, 

73 mobject: Mobject, 

74 target_mobject: Mobject, 

75 transform_mismatches: bool = False, 

76 fade_transform_mismatches: bool = False, 

77 key_map: Mapping[Key, Hashable] | None = None, 

78 **kwargs: Unpack[TransformOptions], 

79 ): 

80 source_map = self.get_shape_map(mobject) 

81 target_map = self.get_shape_map(target_mobject) 

82 key_mapped_source, key_mapped_target = Group(), Group() 

83 for key1, key2 in (key_map or {}).items(): 

84 if key1 in source_map and key2 in target_map: 

85 key_mapped_source.add(source_map.pop(key1)) 

86 key_mapped_target.add(target_map.pop(key2)) 

87 matched = [key for key in source_map if key in target_map] 

88 anims: list[AnimationGroup | Transform] = [ 

89 Transform( 

90 Group(*(source_map[k] for k in matched)), 

91 Group(*(target_map[k] for k in matched)), 

92 **kwargs, 

93 ) 

94 ] 

95 if len(key_mapped_source) > 0: 

96 anims.append( 

97 FadeTransformPieces(key_mapped_source, key_mapped_target, **kwargs) 

98 ) 

99 fade_source = Group( 

100 *(part for key, part in source_map.items() if key not in target_map) 

101 ) 

102 fade_target = Group( 

103 *(part for key, part in target_map.items() if key not in source_map) 

104 ) 

105 fade_target_copy = fade_target.copy() 

106 if transform_mismatches: 

107 kwargs.setdefault("replace_mobject_with_target_in_scene", True) 

108 anims.append(Transform(fade_source, fade_target, **kwargs)) 

109 elif fade_transform_mismatches: 

110 anims.append(FadeTransformPieces(fade_source, fade_target, **kwargs)) 

111 else: 

112 anims.append(FadeOut(fade_source, target_position=fade_target, **kwargs)) 

113 anims.append( 

114 FadeIn(fade_target_copy, target_position=fade_target, **kwargs) 

115 ) 

116 super().__init__(*anims) 

117 self.to_remove = [mobject, fade_target_copy] 

118 self.to_add = target_mobject 

119 

120 def get_shape_map(self, mobject: Mobject) -> dict[Hashable, Group]: 

121 """Gather the parts of a mobject by their keys. 

122 

123 Returns: 

124 For each key, in the order its first part comes, a group of the parts with 

125 that key, in order. 

126 """ 

127 groups: dict[Hashable, tuple[Group, list[Mobject]]] = {} 

128 for part in self.get_mobject_parts(mobject): 

129 key = self.get_mobject_key(part) 

130 if (bucket := groups.get(key)) is None: 

131 groups[key] = bucket = Group(), [] 

132 bucket[1].append(part) 

133 return {key: group.add(*parts) for key, (group, parts) in groups.items()} 

134 

135 def _end(self, i: int) -> None: 

136 # its parts leave the scene with the whole, as it finishes (`clean_up_from_scene`) 

137 self.done.add(i) 

138 self.animations[i].finish() 

139 

140 def clean_up_from_scene(self, scene: Scene) -> None: 

141 for anim in self.animations: 

142 anim.interpolate(0) 

143 # what its parts brought into the scene, and every part of the mobject it 

144 # transformed, wherever the parts brought them 

145 scene.remove( 

146 *(anim.mobject for anim in self.animations), 

147 *(part for mob in self.to_remove for part in mob.get_family()), 

148 ) 

149 scene.add(self.to_add) 

150 

151 @staticmethod 

152 def get_mobject_parts(mobject: Mobject) -> list[Mobject]: 

153 """The parts of a mobject that are matched: a subclass says what they are. 

154 

155 Returns: 

156 Its parts, in order. 

157 """ 

158 raise NotImplementedError("To be implemented in subclass.") 

159 

160 @staticmethod 

161 def get_mobject_key(mobject: Mobject) -> Hashable: 

162 """The key a part is matched by: a subclass says what it is. 

163 

164 Args: 

165 mobject: A part. 

166 

167 Returns: 

168 Its key: parts with equal keys match. 

169 """ 

170 raise NotImplementedError("To be implemented in subclass.") 

171 

172 

173class TransformMatchingShapes(TransformMatchingAbstractBase): 

174 """Transform a mobject into another by matching their shapes: each part moves to a 

175 part of the same shape, and the others fade. 

176 

177 The parts are the members with points (the letters of a text); two match when they 

178 have the same shape, whatever their size and place (their points, centered and 

179 scaled to a height of 1, agree to 3 decimals). So a text becomes its anagram letter 

180 by letter. When the animation finishes, `target_mobject` is in the scene in the 

181 place of `mobject`. 

182 

183 Args: 

184 mobject: The mobject to transform. 

185 target_mobject: The mobject it becomes. 

186 transform_mismatches: Whether the unmatched parts transform into the target's 

187 unmatched parts, rather than fade. 

188 fade_transform_mismatches: Whether they cross-fade into the target's unmatched 

189 parts (see [`FadeTransformPieces`][manimgx.FadeTransformPieces]), rather 

190 than fade. 

191 key_map: Pairs of keys to match although they differ: the parts of `mobject` 

192 with the first key cross-fade into the target's parts with the second. 

193 These matches take precedence over equal keys. 

194 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

195 each of the animations it plays. 

196 

197 Examples: 

198 ```python 

199 import manimgx as m 

200 

201 

202 class TransformMatchingShapesExample(m.Scene): 

203 def construct(self) -> None: 

204 source = m.Text("the morse code", font_size=96) 

205 target = m.Text("here come dots", font_size=96, color=m.YELLOW) 

206 self.add(source) 

207 self.play( 

208 m.TransformMatchingShapes(source, target, path_arc=m.PI / 2), 

209 run_time=2, 

210 ) 

211 self.wait(0.5) 

212 ``` 

213 """ 

214 

215 @staticmethod 

216 def get_mobject_parts(mobject: Mobject) -> list[Mobject]: 

217 return mobject.family_members_with_points() 

218 

219 @staticmethod 

220 def get_mobject_key(mobject: Mobject) -> Hashable: 

221 # the shape itself (centered, unit height, to 3 decimals): its bytes, not their 

222 # hash 

223 shape = mobject.copy().center().set(height=1) 

224 return (np.round(shape.points, 3) + 0.0).tobytes() 

225 

226 

227class TransformMatchingTex(TransformMatchingAbstractBase): 

228 """Transform a formula into another by matching their parts: each part moves to a 

229 part written the same way, and the others fade. 

230 

231 The parts of a [`MathTex`][manimgx.MathTex] are the strings it is made of: the 

232 arguments it is given and what `{{…}}` sets apart in them, split further at its 

233 `substrings_to_isolate` and at the strings of its `tex_to_color_map` (a group's 

234 parts are its members'). Two parts 

235 match when their strings are the same, so give each term that should travel as an 

236 argument of its own. When the animation finishes, `target_mobject` is in the scene 

237 in the place of `mobject`. 

238 

239 Args: 

240 mobject: The formula to transform: a `MathTex`, or a group of them. 

241 target_mobject: The formula it becomes. 

242 transform_mismatches: Whether the unmatched parts transform into the target's 

243 unmatched parts, rather than fade. 

244 fade_transform_mismatches: Whether they cross-fade into the target's unmatched 

245 parts (see [`FadeTransformPieces`][manimgx.FadeTransformPieces]), rather 

246 than fade. 

247 key_map: Pairs of strings to match although they differ: the parts of `mobject` 

248 written the first way cross-fade into the target's parts written the second. 

249 These matches take precedence over equal keys. 

250 **kwargs: [Transform options][manimgx.animation.transform.TransformOptions] for 

251 each of the animations it plays. 

252 

253 Examples: 

254 ```python 

255 import manimgx as m 

256 

257 

258 class TransformMatchingTexExample(m.Scene): 

259 def construct(self) -> None: 

260 before = m.MathTex("a^2", "+", "b^2", "=", "c^2", font_size=120) 

261 after = m.MathTex("a^2", "=", "c^2", "-", "b^2", font_size=120) 

262 self.add(before) 

263 self.play( 

264 m.TransformMatchingTex(before, after, path_arc=m.PI / 2), run_time=2 

265 ) 

266 self.wait(0.5) 

267 ``` 

268 """ 

269 

270 @staticmethod 

271 def get_mobject_parts(mobject: Mobject) -> list[Mobject]: 

272 if isinstance(mobject, Group): 

273 return [ 

274 p 

275 for s in mobject.submobjects 

276 for p in TransformMatchingTex.get_mobject_parts(s) 

277 ] 

278 return mobject.submobjects 

279 

280 @staticmethod 

281 def get_mobject_key(mobject: Mobject) -> Hashable: 

282 assert isinstance(mobject, MathTexPart) 

283 return mobject.tex_string