Skip to content

Instantly share code, notes, and snippets.

@uwezi
Last active February 17, 2024 11:55
Show Gist options
  • Save uwezi/7c13298b38aa6b76f42b6a972d9a6b6f to your computer and use it in GitHub Desktop.
Save uwezi/7c13298b38aa6b76f42b6a972d9a6b6f to your computer and use it in GitHub Desktop.
[shape in TeX] Abulafia's smart search routine. #manim #latex #shape
# https://discord.com/channels/581738731934056449/1207779001041551440/1208377356155097092
def search_shape_in_text(text:VMobject, shape:VMobject, index=0):
def get_mobject_key(mobject: Mobject) -> int:
mobject.save_state().center().scale_to_fit_height(1)
r = np.array2string(mobject.points, precision=2,
separator=' ', suppress_small=True, threshold=None)
r = r.replace('-0. ', ' 0. ')
mobject.restore()
return hash(r)
results = []
l = len(shape.submobjects[0])
shape_aux = VMobject()
shape_aux.points = np.concatenate([p.points for p in shape.submobjects[0]])
for i in range(len(text.submobjects[index])-l+1):
subtext = VMobject()
subtext.points = np.concatenate([p.points for p in text.submobjects[index][i:i+l]])
if get_mobject_key(subtext) == get_mobject_key(shape_aux):
results.append(slice(i, i+l))
return results
def search_shapes_in_text(text:VMobject, shapes, index=0):
results = []
for shape in shapes:
results += search_shape_in_text(text, shape, index)
return results
def group_shapes_in_text(text: VMobject, shapes, index = 0):
if isinstance(shapes, VMobject):
shapes = [shapes]
results = search_shapes_in_text(text, shapes, index)
return VGroup(*[text[index][s] for s in results])
def colorize_similar_tex(eq, config):
for key, color in config.items():
group_shapes_in_text(eq, MathTex(key)).set_color(color)
return eq
class Test(Scene):
def construct(self):
x_equ_1 = MathTex(r"x = \frac{-b \pm \sqrt{D}}{2a}")
x_equ_2 = MathTex(r"x = -\frac{b}{2a}").next_to(x_equ_1, DOWN)
x_equ_3 = MathTex(r"x \neq \mathbb{R}").next_to(x_equ_2, DOWN)
color_config = { "a": RED, "b": BLUE }
self.add(colorize_similar_tex(x_equ_1.copy(), color_config))
self.add(colorize_similar_tex(x_equ_2.copy(), color_config))
self.add(colorize_similar_tex(x_equ_3.copy(), color_config))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment