The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add waves and optics examples
apoogdk51a81f4e262c
diff --git a/examples/cherenkov_cone.py b/examples/cherenkov_cone.pynew file mode 100644index 00000000..eaa9608d--- /dev/null+++ b/examples/cherenkov_cone.py@@ -0,0 +1,558 @@+"""Outrunning light: a charge in water leaves a cone of blue light behind it.++Light in water travels at c/n (n = 1.33). Every point a charge passes sends out a wavelet growing+at c/n: below β = 1/n they nest; above it they pile up on a cone, the optical sonic boom, and+light leaves along its normal at the Cherenkov angle cos θ = 1/(nβ) (Cherenkov 1934; Frank & Tamm+1937), 41° in water as β → 1. On screen θ is fitted to the drawn wavefronts at three speeds;+photons leave the track at θ, as bright as Frank–Tamm says (∝ sin²θ). When the charge slows below+c/n the light goes out, and the shell already emitted lands on a wall of photomultipliers as a+ring: how Super-Kamiokande sees a muon.+"""++from collections.abc import Callable++import numpy as np++import manimgx as m++N_WATER = 1.33+WAVE = 1.15 # c/n: how fast every wavelet grows (scene units per second)+LIGHT = N_WATER * WAVE # c+LIFE = 2.8 # seconds a wavelet is drawn behind the charge+# photons are absorbed at this age (the water's attenuation, shortened)+PHOTON_LIFE = 3.5+TICK = 1 / 60+RING_EVERY = 6 # simulation ticks between drawn wavelets (0.1 s)+# photons leave every tick at these azimuths: each azimuth traces one line of the cone+AZIMUTHS = 96+PHOTON_CAP = AZIMUTHS * 220+APEX_X = 2.0 # where the charge sits on screen while the camera follows it+FIT_AGES = (0.15, 0.8) # the envelope is fitted to the wavelets just behind the charge+PMT_PITCH = 0.15+PMT_RADIUS = 3.4+BRAKE = 2.4 # the charge starts to slow down this far before the wall+WATER = "#020a17"+RING_BLUE = "#8fd3ff"+CHERENKOV = ["#ffffff", "#9ddcff", "#3fa9ff", "#1f5fd6"]+HIT_TIME = ["#fff3b0", "#ffb347", "#ff5e62", "#c84bff", "#4b6bff"]+++def colormap(values: np.ndarray, stops: list[str]) -> np.ndarray:+ """(n, 4) RGBA rows for values in [0, 1], interpolated through color stops."""+ rgb = np.array([m.ManimColor(s).to_rgb() for s in stops])+ x = np.clip(values, 0, 1) * (len(stops) - 1)+ i = np.minimum(x.astype(int), len(stops) - 2)+ f = (x - i)[:, None]+ out = np.ones((len(values), 4))+ out[:, :3] = rgb[i] * (1 - f) + rgb[i + 1] * f+ return out+++def cloud(count: int, size: float) -> m.PMobject:+ mob = m.PMobject(stroke_width=size)+ mob.add_points(np.zeros((count, 3)), rgbas=np.zeros((count, 4)))+ return mob+++class Tank:+ """The charge, its wavelets and its photons, in the lab frame; the camera follows the charge+ (`shift` is the lab x drawn at the screen's x = 0) until `follow` is animated to 0.+ """++ def __init__(self, beta: m.ValueTracker, follow: m.ValueTracker) -> None:+ self.beta = beta+ self.follow = follow+ self.time = 0.0+ self.ticks = 0+ self.x = 0.0+ self.speed = beta.get_value() # measured: distance per tick over c+ self.shift = -APEX_X+ self.wall = np.inf+ self.brake_time = np.inf # when the charge began to slow down+ rings = int(LIFE / (RING_EVERY * TICK)) + 2+ self.ring_x = np.zeros(rings)+ self.ring_t = np.full(rings, -np.inf)+ self.photon_x = np.zeros(PHOTON_CAP) # emission point on the track+ self.photon_dir = np.zeros((PHOTON_CAP, 3))+ self.photon_t = np.full(PHOTON_CAP, -np.inf)+ # brightness per photon: Frank–Tamm, ∝ sin²θ per unit length+ self.photon_w = np.zeros(PHOTON_CAP)+ self.alive = np.zeros(PHOTON_CAP, bool)+ self.next_photon = 0+ # the wall's photomultipliers: a square grid of tubes inside a disc, facing the track+ g = np.arange(-PMT_RADIUS, PMT_RADIUS + 1e-9, PMT_PITCH)+ yy, zz = np.meshgrid(g, g, indexing="ij")+ self.pmt_side = len(g)+ self.pmt_inside = (np.hypot(yy, zz) <= PMT_RADIUS).ravel()+ self.pmt_yz = np.stack([yy.ravel(), zz.ravel()], axis=1)+ self.pmt_flash = np.zeros(len(self.pmt_yz))+ self.pmt_charge = np.zeros(len(self.pmt_yz))+ self.pmt_first = np.full(len(self.pmt_yz), np.inf)++ # ── the simulation: one 60 Hz tick ──────────────────────────────────────────────────────+ def step(self, dt: float) -> None:+ if dt <= 0:+ return+ beta = self.beta.get_value()+ if beta < 0.985 and self.x > 0 and np.isfinite(self.wall):+ self.brake_time = min(self.brake_time, self.time)+ before = self.x+ self.x += beta * LIGHT * dt+ self.speed = (self.x - before) / dt / LIGHT+ self.shift += self.follow.get_value() * (self.x - before)+ self.time += dt+ self.ticks += 1+ if beta > 0.3 and self.ticks % RING_EVERY == 0:+ k = int(np.argmin(self.ring_t)) # reuse the oldest slot+ self.ring_x[k], self.ring_t[k] = self.x, self.time+ if N_WATER * beta > 1: # faster than light in water: it shines+ self.emit(beta)+ self.alive &= self.time - self.photon_t < PHOTON_LIFE+ self.absorb()+ self.pmt_flash *= np.exp(-dt / 0.35)++ def emit(self, beta: float) -> None:+ """Photons leave the track at the Cherenkov angle, all around it."""+ cos_t = 1 / (N_WATER * beta)+ sin2 = 1 - cos_t**2+ count = AZIMUTHS+ idx = (self.next_photon + np.arange(count)) % PHOTON_CAP+ self.next_photon = (self.next_photon + count) % PHOTON_CAP+ az = np.linspace(0, 2 * np.pi, count, endpoint=False)+ sin_t = np.sqrt(sin2)+ self.photon_w[idx] = beta * sin2 / (1 - 1 / N_WATER**2)+ self.photon_dir[idx] = np.stack(+ [np.full(count, cos_t), sin_t * np.cos(az), sin_t * np.sin(az)], axis=1+ )+ self.photon_x[idx] = self.x+ self.photon_t[idx] = self.time+ self.alive[idx] = True++ def photons(self) -> np.ndarray:+ """Lab positions of all photon slots."""+ age = self.time - self.photon_t+ pos = WAVE * np.where(np.isfinite(age), age, 0)[:, None] * self.photon_dir+ pos[:, 0] += self.photon_x+ return pos++ def absorb(self) -> None:+ """Photons crossing the wall plane this tick are caught by the nearest tube."""+ if not np.isfinite(self.wall):+ return+ pos = self.photons()+ crossed = self.alive & (pos[:, 0] >= self.wall)+ if not crossed.any():+ return+ idx = np.nonzero(crossed)[0]+ # where each photon met the plane+ age = (self.wall - self.photon_x[idx]) / (WAVE * self.photon_dir[idx, 0])+ yz = WAVE * age[:, None] * self.photon_dir[idx, 1:]+ cell = np.round((yz + PMT_RADIUS) / PMT_PITCH).astype(int)+ cell = np.clip(cell, 0, self.pmt_side - 1)+ tube = cell[:, 0] * self.pmt_side + cell[:, 1]+ np.add.at(self.pmt_flash, tube, self.photon_w[idx])+ np.add.at(self.pmt_charge, tube, self.photon_w[idx])+ self.pmt_first[tube] = np.minimum(self.pmt_first[tube], self.time)+ self.alive[idx] = False++ # ── the measurement ─────────────────────────────────────────────────────────────────────+ def fitted_angle(self) -> float | None:+ """θ fitted to the drawn wavefronts: the least-squares line through the charge touching+ the wavelets emitted 0.15–0.8 s ago; the light leaves along its normal. None while the+ charge is still inside its own wavelets: then there is no cone."""+ age = self.time - self.ring_t+ chosen = (age > FIT_AGES[0]) & (age < FIT_AGES[1])+ if chosen.sum() < 3:+ return None+ behind = self.x - self.ring_x[chosen]+ radius = WAVE * age[chosen]+ s = radius / behind+ if np.any(s >= 1):+ return None+ # the point where the line from the charge touches each wavefront (charge at origin)+ tx = -behind + radius * s+ ty = radius * np.sqrt(1 - s * s)+ alpha = np.arctan(-(tx * ty).sum() / (tx * tx).sum())+ return float(np.pi / 2 - alpha)+++class CherenkovCone(m.ThreeDScene):+ def construct(self) -> None:+ self.camera.background_color = WATER+ self.set_camera_orientation(phi=0, theta=-90 * m.DEGREES, zoom=0.92)+ beta = m.ValueTracker(0.60)+ follow = m.ValueTracker(1.0) # 1: the camera rides with the charge+ glow = m.ValueTracker(0.0) # the photons' visibility+ rings_on = m.ValueTracker(1.0)+ fit_on = m.ValueTracker(0.0)+ track_on = m.ValueTracker(1.0)+ wall_on = m.ValueTracker(0.0)+ charge_on = m.ValueTracker(1.0)+ tank = Tank(beta, follow)+ for _ in range(int(LIFE / TICK)): # start with a full train of wavelets+ tank.step(TICK)++ def here(lab_x: float) -> np.ndarray:+ return np.array([lab_x - tank.shift, 0.0, 0.0])++ # ── wavelets: one circle per slot of the ring buffer ────────────────────────────────+ template = m.Circle(radius=1).points.copy()+ circles = [+ m.Circle(radius=1, stroke_width=1.7, color=RING_BLUE) for _ in tank.ring_t+ ]+ rings = m.VGroup(*circles)++ def draw_rings(_: m.Mobject) -> None:+ ages = tank.time - tank.ring_t+ for circle, age, x in zip(circles, ages, tank.ring_x, strict=True):+ if not 0 <= age < LIFE:+ circle.set_stroke(opacity=0)+ continue+ circle.points = template * max(WAVE * age, 0.01) + here(x)+ fade = (1 - age / LIFE) ** 1.4+ circle.set_stroke(opacity=0.9 * fade * rings_on.get_value())++ rings.add_updater(draw_rings)++ # ── photons on the cone ──────────────────────────────────────────────────────────────+ photons = cloud(PHOTON_CAP, 2.6)+ photon_halo = cloud(PHOTON_CAP, 8.0) # a soft bloom around every photon++ def draw_photons(mob: m.Mobject) -> None:+ pos = tank.photons()+ pos[:, 0] -= tank.shift+ age = np.nan_to_num((tank.time - tank.photon_t) / PHOTON_LIFE, posinf=1)+ rows = colormap(age, CHERENKOV)+ # brighter bands (photons emitted together) slide down the cone: each is where one+ # wavelet touches it+ pulse = 0.65 + 0.35 * np.cos(2 * np.pi * 2.5 * tank.photon_t)+ fade = np.clip((1 - age) / 0.3, 0, 1) * tank.photon_w * pulse+ shown = np.where(tank.alive, fade, 0) * glow.get_value()+ for layer, alpha in ((mob, 1.0), (photon_halo, 0.07)):+ rows[:, 3] = alpha * shown+ layer.points = pos+ layer.paint = layer.paint.but(fill=rows.copy())++ photons.add_updater(draw_photons)++ # ── water specks: they show the motion ──────────────────────────────────────────────+ rng = np.random.default_rng(3)+ speck_lab = rng.uniform([-12, -4.5, -4.5], [12, 4.5, 4.5], (420, 3))+ specks = cloud(len(speck_lab), 1.8)++ def draw_specks(mob: m.Mobject) -> None:+ pos = speck_lab.copy()+ pos[:, 0] = (pos[:, 0] - tank.shift + 12) % 24 - 12+ rows = np.tile([0.55, 0.7, 0.85, 0.0], (len(pos), 1))+ rows[:, 3] = 0.3 * np.clip((11.5 - np.abs(pos[:, 0])) / 2, 0, 1)+ mob.points = pos+ mob.paint = mob.paint.but(fill=rows)++ specks.add_updater(draw_specks)++ # ── the charge, its halo and its track ──────────────────────────────────────────────+ charge = m.Dot3D(radius=0.07, color=m.WHITE)+ halos = [cloud(1, w) for w in (12, 24, 44)]+ track = m.VMobject(stroke_color=m.WHITE, stroke_width=1.5)++ def draw_charge(mob: m.Mobject) -> None:+ p = here(tank.x)+ shown = charge_on.get_value()+ mob.move_to(p)+ mob.set_opacity(shown)+ for halo, a in zip(halos, (0.5, 0.18, 0.07), strict=True):+ halo.points = p[None, :]+ halo.paint = halo.paint.but(+ fill=np.array([[0.62, 0.86, 1.0, a * shown]])+ )+ track.set_points_as_corners([p - np.array([7.5, 0, 0]), p])+ track.set_stroke(opacity=0.3 * track_on.get_value())++ charge.add_updater(draw_charge)++ # ── the fitted envelope, a light ray and its angle ──────────────────────────────────+ def fit_marks() -> m.VGroup:+ theta = tank.fitted_angle()+ show = fit_on.get_value()+ if theta is None or show < 0.01:+ return m.VGroup()+ alpha = np.pi / 2 - theta+ apex = here(tank.x)+ lines = m.VGroup(+ *[+ m.DashedLine(+ apex,+ apex+ + 3.4 * np.array([-np.cos(alpha), sign * np.sin(alpha), 0]),+ dash_length=0.12,+ stroke_width=2.4,+ color=m.GOLD,+ )+ for sign in (1, -1)+ ]+ )+ # a ray from 2.6 behind the charge to the envelope, normal to it+ back = 2.6+ source = apex - np.array([back, 0, 0])+ foot = apex + back * np.cos(alpha) * np.array(+ [-np.cos(alpha), np.sin(alpha), 0]+ )+ ray = m.Arrow(+ source,+ foot,+ buff=0,+ stroke_width=3,+ color=m.GOLD,+ max_tip_length_to_length_ratio=0.12,+ )+ arc = m.Arc(radius=0.55, start_angle=0, angle=theta, arc_center=source)+ arc.set_stroke(m.GOLD, 2)+ label = m.MathTex(r"\theta", font_size=30, color=m.GOLD).move_to(+ source + 0.82 * np.array([np.cos(theta / 2), np.sin(theta / 2), 0])+ )+ marks = m.VGroup(lines, ray, arc, label)+ marks.set_opacity(show)+ return marks++ fit = m.always_redraw(fit_marks)++ # ── the wall of photomultipliers ─────────────────────────────────────────────────────+ inside = tank.pmt_inside+ pmts = cloud(int(inside.sum()), 8.0)++ def draw_wall(mob: m.Mobject) -> None:+ x = tank.wall - tank.shift if np.isfinite(tank.wall) else 40.0+ yz = tank.pmt_yz[inside]+ mob.points = np.column_stack([np.full(len(yz), x), yz])+ on = wall_on.get_value()+ first = tank.pmt_first[inside]+ hit = np.isfinite(first)+ # color by arrival time, across the half second in which the ring lands+ start = tank.brake_time + 2.55 if np.isfinite(tank.brake_time) else 0.0+ timed = colormap(np.where(hit, (first - start) / 0.55, 0), HIT_TIME)+ caught = tank.pmt_charge[inside] # photons caught, Frank–Tamm weighted+ light = np.clip(caught / 4.0, 0, 1)[:, None]+ flash = np.clip(tank.pmt_flash[inside] / 2.0, 0, 1)[:, None]+ rows = np.tile([0.3, 0.36, 0.45, 0.0], (len(yz), 1))+ rows[:, :3] = rows[:, :3] * (1 - light) + timed[:, :3] * light+ rows[:, :3] = rows[:, :3] * (1 - flash) + flash+ lit = np.maximum(0.3 + 0.7 * light, flash)[:, 0]+ rows[:, 3] = on * np.where(hit, lit, 0.2)+ mob.paint = mob.paint.but(fill=rows)++ pmts.add_updater(draw_wall)++ driver = m.ValueTracker(0)+ driver.add_updater(lambda _, dt: tank.step(dt))++ # ── heads-up display ─────────────────────────────────────────────────────────────────+ title = m.Text("Outrunning light", font_size=38).to_corner(m.UL)+ subtitle = m.Text(+ "a charge moving faster than light does in water", font_size=22+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)++ law = m.MathTex(r"\cos\theta = \frac{1}{n\beta}", font_size=40)+ medium = m.MathTex(r"n = 1.33\ \text{(water)}", font_size=26).set_color(+ m.GREY_B+ )+ law_block = m.VGroup(law, medium).arrange(m.DOWN, buff=0.15)+ law_block.to_corner(m.UR).shift(0.1 * m.LEFT)++ def readout(tex: str, value: m.DecimalNumber) -> m.VGroup:+ return m.VGroup(m.MathTex(tex, font_size=30), value).arrange(+ m.RIGHT, buff=0.15+ )++ beta_value = m.DecimalNumber(0.6, num_decimal_places=3, font_size=30)+ beta_value.add_updater(lambda d: d.set_value(tank.speed))+ fitted_value = m.DecimalNumber(+ 0, num_decimal_places=1, font_size=30, unit=r"^\circ", color=m.GOLD+ )+ formula_value = m.DecimalNumber(+ 0, num_decimal_places=1, font_size=30, unit=r"^\circ"+ )++ def fitted(d: m.DecimalNumber) -> None:+ theta = tank.fitted_angle()+ d.set_value(0 if theta is None else np.degrees(theta))+ d.set_opacity(0 if theta is None else 1)++ def formula(d: m.DecimalNumber) -> None:+ ok = N_WATER * tank.speed > 1+ d.set_value(np.degrees(np.arccos(1 / (N_WATER * tank.speed))) if ok else 0)+ d.set_opacity(1 if ok else 0)++ fitted_value.add_updater(fitted)+ formula_value.add_updater(formula)+ rows = m.VGroup(+ readout(r"\beta =", beta_value),+ readout(r"\theta_{\text{fit}} =", fitted_value),+ readout(r"\arccos\tfrac{1}{n\beta} =", formula_value),+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.18)+ rows.next_to(law_block, m.DOWN, buff=0.4).align_to(law_block, m.LEFT)+ no_cone = m.Text("no cone", font_size=24).set_color(m.GREY_B)+ no_cone.next_to(rows[1][0], m.RIGHT, buff=0.15)+ no_cone.add_updater(+ lambda t: t.set_opacity(0 if tank.fitted_angle() is not None else 1)+ )+ no_angle = m.Text("none", font_size=24).set_color(m.GREY_B)+ no_angle.next_to(rows[2][0], m.RIGHT, buff=0.15)+ no_angle.add_updater(+ lambda t: t.set_opacity(0 if N_WATER * tank.speed > 1 else 1)+ )++ # θ(β): the law, the threshold, the live fit and the measured points+ axes = m.Axes(+ x_range=[0.6, 1.0, 0.1],+ y_range=[0, 45, 15],+ x_length=3.4,+ y_length=2.0,+ tips=False,+ axis_config={"stroke_width": 1.5, "color": m.GREY_B},+ )+ axes.to_corner(m.DR).shift(0.25 * m.UP + 0.35 * m.LEFT)+ threshold = 1 / N_WATER+ curve = axes.plot(+ lambda b: np.degrees(np.arccos(min(1.0, 1 / (N_WATER * b)))),+ x_range=[threshold, 1.0, 0.002],+ color=CHERENKOV[2],+ stroke_width=2.5,+ )+ cut = m.DashedLine(+ axes.c2p(threshold, 0), axes.c2p(threshold, 45), stroke_width=1.5+ ).set_color(m.GREY_B)+ labels = m.VGroup(+ m.MathTex(r"\beta", font_size=28).next_to(+ axes.c2p(1.0, 0), m.RIGHT, buff=0.15+ ),+ m.MathTex(r"1", font_size=24).next_to(axes.c2p(1.0, 0), m.DOWN, buff=0.12),+ m.MathTex(r"\tfrac{1}{n}", font_size=26).next_to(+ axes.c2p(threshold, 0), m.DOWN, buff=0.12+ ),+ m.MathTex(r"\theta", font_size=28).next_to(+ axes.c2p(0.6, 45), m.UP, buff=0.12+ ),+ m.MathTex(r"45^\circ", font_size=22).next_to(+ axes.c2p(0.6, 45), m.LEFT, buff=0.12+ ),+ )+ live = m.Dot(radius=0.06, color=m.GOLD)++ def track_live(d: m.Mobject) -> None:+ theta = tank.fitted_angle()+ b = float(np.clip(tank.speed, 0.6, 1.0))+ d.move_to(axes.c2p(b, 0 if theta is None else np.degrees(theta)))++ live.add_updater(track_live)+ plot = m.VGroup(axes, curve, cut, labels)++ # translucent points hide what is drawn after them behind them: add those last+ self.add(driver, specks, track, rings, pmts, charge, fit)+ self.add(photons, photon_halo, *halos)+ readouts = m.VGroup(rows, no_cone, no_angle, live)+ self.add_fixed_in_frame_mobjects(title, subtitle, law_block, readouts, plot)+ self.remove(title, subtitle, law_block, readouts, plot)++ def stamp() -> None:+ """Put the fitted angle at this speed on the plot."""+ theta = tank.fitted_angle()+ if theta is None:+ return+ dot = m.Dot(+ axes.c2p(tank.speed, np.degrees(theta)), radius=0.07, color=m.WHITE+ )+ ring = m.Circle(radius=0.13, stroke_width=2, color=m.WHITE).move_to(dot)+ self.add_fixed_in_frame_mobjects(dot, ring)+ self.remove(dot, ring)+ self.play(m.FadeIn(dot, scale=2), m.FadeIn(ring, scale=0.4), run_time=0.4)++ # 0–3 s: below the threshold the wavelets nest inside each other+ self.play(m.Write(title), m.FadeIn(subtitle), run_time=1.5)+ self.play(m.FadeIn(law_block), m.FadeIn(readouts), m.FadeIn(plot), run_time=1.2)+ self.wait(0.3)+ # 3–12 s: faster, through the threshold; the cone is fitted at three speeds+ self.play(beta.animate.set_value(0.80), run_time=1.8)+ self.play(fit_on.animate.set_value(1), run_time=0.8)+ self.wait(0.6)+ stamp()+ self.play(beta.animate.set_value(0.90), run_time=1.2)+ self.wait(0.9)+ stamp()+ self.play(beta.animate.set_value(0.99), run_time=1.2)+ self.wait(0.9)+ stamp()+ # 12–18 s: the cone in 3D, lit by its photons+ self.move_camera(+ phi=64 * m.DEGREES,+ theta=-118 * m.DEGREES,+ zoom=1.0,+ frame_center=np.array([0.7, -0.15, 0.3]),+ run_time=3.5,+ added_anims=[+ glow.animate.set_value(1),+ rings_on.animate.set_value(0.3),+ track_on.animate.set_value(0.5),+ fit_on.animate.set_value(0),+ ],+ )+ orbit = 4.5+ tank.wall = tank.x + BRAKE + beta.get_value() * LIGHT * orbit+ self.play(+ self.camera.theta_tracker.animate.set_value(-72 * m.DEGREES),+ self.camera.phi_tracker.animate.set_value(70 * m.DEGREES),+ run_time=orbit,+ )+ # 20–23 s: the charge slows below c/n: the cone closes and goes dark; the camera lets+ # it go and turns to the wall, where the light already emitted lands as a ring+ swing = 2.6+ wall_x = tank.wall - tank.shift - 0.15 # where it stops once the camera does++ def within(+ seconds: float, rate: Callable[[float], float] = m.smooth+ ) -> Callable[[float], float]:+ """A rate function that completes in the first `seconds` of the swing."""+ return lambda t: rate(min(1.0, t * swing / seconds))++ self.move_camera(+ phi=84 * m.DEGREES,+ theta=-10 * m.DEGREES,+ zoom=0.9,+ frame_center=np.array([wall_x, 1.33, 0.33]),+ run_time=swing,+ added_anims=[+ beta.animate(rate_func=within(1.6, m.rush_from)).set_value(0.0),+ follow.animate(rate_func=within(0.8, m.rush_from)).set_value(0.0),+ wall_on.animate(rate_func=within(1.2)).set_value(1),+ rings_on.animate.set_value(0),+ track_on.animate.set_value(0),+ charge_on.animate.set_value(0),+ ],+ )+ self.play(+ m.FadeOut(readouts),+ self.camera.theta_tracker.animate.set_value(-18 * m.DEGREES),+ run_time=3.0,+ rate_func=m.linear,+ )+ closing = m.Text(+ "Super-Kamiokande sees a stopping muon as a ring like this", font_size=26+ )+ closing.to_edge(m.DOWN, buff=0.3).to_edge(m.LEFT, buff=0.4)+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(+ m.FadeIn(closing, shift=0.2 * m.UP),+ self.camera.theta_tracker.animate.set_value(-22 * m.DEGREES),+ run_time=1.4,+ rate_func=m.linear,+ )+ self.play(+ self.camera.theta_tracker.animate.set_value(-30 * m.DEGREES),+ run_time=3.2,+ rate_func=m.linear,+ )+++if __name__ == "__main__":+ CherenkovCone().render("cherenkov_cone.mp4")diff --git a/examples/harmonic_drive.py b/examples/harmonic_drive.pynew file mode 100644index 00000000..8607cee7--- /dev/null+++ b/examples/harmonic_drive.py@@ -0,0 +1,601 @@+"""Strain-wave gearing: 30:1 in one flat ring.++An elliptical plug (the wave generator) spins inside a thin ring of 60 teeth (the flexspline) and+flexes it into mesh with a rigid ring of 62 teeth (the circular spline) at the two ends of its long+axis. The thin ring cannot stretch, so where it bulges out by one module its teeth sit exactly one+gap apart and slide straight in and out of the gaps. Each turn of the plug carries the mesh past+all 62 gaps but only 60 teeth, so the flexspline walks back two teeth a turn:+β = −(N_c − N_f)/N_f · ψ = −ψ/30 (C. W. Musser, 1957). The circular spline's teeth are cut here as+the envelope of the flexspline's own moving teeth, so the two never collide.+"""++from collections.abc import Callable+from itertools import pairwise++import numpy as np++import manimgx as m+++def camera_axes(phi: float, theta: float, gamma: float) -> np.ndarray:+ """The camera's axes for its orbit angles, as rows: right, up, and toward the viewer."""++ def spin(a: float) -> np.ndarray: # a turn about z+ return np.array(+ [[np.cos(a), -np.sin(a), 0.0], [np.sin(a), np.cos(a), 0.0], [0.0, 0.0, 1.0]]+ )++ c, s = np.cos(phi), np.sin(phi)+ tilt = np.array(+ [[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]+ ) # a turn by −φ about x+ return spin(gamma) @ tilt @ spin(-theta - np.pi / 2)+++NF, NC = 60, 62 # flexspline and circular spline teeth+MOD = 0.1 # module: the flexspline's pitch radius is NF · MOD / 2+RP, W0 = NF * MOD / 2, (NC - NF) * MOD / 2 # pitch radius; the bulge at the long axis+PITCH = np.pi * MOD # tooth pitch along the pitch line+DELTA = m.TAU / NC # the circular spline's pitch angle+HA, HF, RIM = 0.8 * MOD, 0.9 * MOD, 1.3 * MOD # tooth tip and root; rim under the root+THICK = 0.5 * PITCH # tooth thickness on the pitch line+FLANK = np.radians(25) # flank angle+BALL, BALLS = 0.1, 36 # bearing balls between the plug and the flexspline+CAM = -HF - RIM - 2 * BALL # the plug's rim, below the pitch line+CLEAR, R_OUT, HUB = 0.006, RP + 5.5 * MOD, 0.55 # tooth clearance; outer rim; shaft+STEEL, BRASS, RED = "#5d6879", "#d8b15e", "#e63946"+PLUG, PLUG_LIGHT = "#1d5a56", "#4fc1b5"+# plug speed (turns per second) at key times, eased between them+SPEED = [(0, 0), (8.6, 0), (10.2, 0.5), (19.2, 0.5), (21.2, 0.04), (25.2, 0.04)]+SPEED += [(27.0, 0.3), (31.0, 0.3)]+CLOSE_UP = 23.2 # the red tooth meets the long axis in the close-up+Face = tuple[np.ndarray, np.ndarray, list[np.ndarray]] # points, triangles, loops+++def pitch_line(+ theta: np.ndarray, w: float+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """The flexspline's pitch line, bulged by w along the plug's long axis (angle 0), at material+ angles θ: an inextensible ring, radial shift w cos 2θ and tangential shift −(w/2) sin 2θ.+ Returns points, unit tangents and outward normals (each (n, 2))."""+ rho = RP + w * np.cos(2 * theta)+ phi = theta - w / (2 * RP) * np.sin(2 * theta)+ d_rho, d_phi = -2 * w * np.sin(2 * theta), 1 - w / RP * np.cos(2 * theta)+ radial = np.stack([np.cos(phi), np.sin(phi)], -1)+ across = np.stack([-np.sin(phi), np.cos(phi)], -1)+ tangent = d_rho[:, None] * radial + (rho * d_phi)[:, None] * across+ tangent /= np.linalg.norm(tangent, axis=1, keepdims=True)+ normal = np.stack([tangent[:, 1], -tangent[:, 0]], -1)+ return rho[:, None] * radial, tangent, normal+++def turn(points: np.ndarray, angle: float) -> np.ndarray:+ """Points (n, 2) turned counterclockwise by angle."""+ c, s = np.cos(angle), np.sin(angle)+ return points @ np.array([[c, s], [-s, c]])+++def polar(r: np.ndarray, angle: np.ndarray) -> np.ndarray:+ return np.stack([r * np.cos(angle), r * np.sin(angle)], -1)+++def tooth_cell() -> np.ndarray:+ """One flexspline pitch cell (x along the pitch line, y out of it), 14 points from x = −p/2 to+ x = p/2: root, a tooth with straight flanks and rounded tip corners, root."""+ half, slope = THICK / 2, np.tan(FLANK)+ fillet = 0.3 * (half - HA * slope)+ cy = HA - fillet # the fillet touches the tip line and the flank+ cx = (half * np.cos(FLANK) - cy * np.sin(FLANK) - fillet) / np.cos(FLANK)+ arc = np.linspace(np.pi - FLANK, np.pi / 2, 5)+ corner = np.stack([-cx + fillet * np.cos(arc), cy + fillet * np.sin(arc)], -1)+ left = np.vstack([[-PITCH / 2, -HF], [-half - HF * slope, -HF], corner])+ return np.vstack([left, (left * [-1, 1])[::-1]])+++def place_teeth(cell: np.ndarray, psi: float, w: float) -> np.ndarray:+ """Every tooth's copy of `cell` (NF, k, 2), each tooth rigid on its pitch-line spot, for the+ plug turned by ψ: the flexspline itself has turned by β = −ψ (NC − NF) / NF."""+ theta = m.TAU * np.arange(NF) / NF - psi * NC / NF # material angles from the axis+ spot, tangent, normal = pitch_line(theta, w)+ pts = spot[:, None] + cell[:, :1] * tangent[:, None] + cell[:, 1:] * normal[:, None]+ return turn(pts.reshape(-1, 2), psi).reshape(NF, len(cell), 2)+++def spline_tooth(cell: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """The circular spline's tooth, cut as the envelope of the flexspline's teeth: the half-angle+ of the region they sweep through one gap, at each radius, subtracted from the pitch. The+ motion repeats, turned by one gap, every 1/62 turn of the plug, so that stretch covers all+ gaps. Returns the tooth's radii (tip → root) and half-angles."""+ deep = np.array([[PITCH / 2, -HF - RIM], [-PITCH / 2, -HF - RIM]])+ outline = np.vstack([cell, deep, cell[:1]]) # everything under the outline counts+ radii = np.linspace(RP - W0 - HF, RP + W0 + HA, 600)+ swept = np.zeros(len(radii))+ for psi in np.linspace(0, DELTA, 128, endpoint=False):+ pts = place_teeth(outline, psi, W0)+ middle = place_teeth(np.zeros((1, 2)), psi, W0)[:, 0]+ gap = np.round(np.arctan2(middle[:, 1], middle[:, 0]) / DELTA) * DELTA+ r = np.linalg.norm(pts, axis=-1)+ ang = np.arctan2(pts[..., 1], pts[..., 0]) - gap[:, None]+ ang = np.abs((ang + np.pi) % m.TAU - np.pi)[..., None]+ r = r[..., None]+ # where each edge of each outline crosses each radius, and at what angle+ f = (radii - r[:, :-1]) / np.where(+ r[:, 1:] == r[:, :-1], 1e-12, r[:, 1:] - r[:, :-1]+ )+ crossing = ang[:, :-1] + f * (ang[:, 1:] - ang[:, :-1])+ crossing = np.where((f >= 0) & (f <= 1), crossing, 0)+ swept = np.maximum(swept, crossing.max(axis=(0, 1)))+ half = DELTA / 2 - swept - CLEAR / radii+ solid = np.flatnonzero(half > 0)+ keep = np.linspace(solid[0], len(radii) - 1, 14).round().astype(int)+ return radii[keep], half[keep]+++def prism(+ face: np.ndarray, tris: np.ndarray, loops: list[np.ndarray], z0: float, z1: float+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """A flat part: its top face (points, triangles) at height z1 and a wall down to z0 along+ each closed boundary loop. Faces and walls share no vertices, so their edges stay crisp.+ Returns, per vertex, the face point it copies and its height, and the triangles."""+ source, height, faces = [np.arange(len(face))], [np.full(len(face), z1)], [tris]+ count = len(face)+ for loop in loops:+ n = len(loop)+ source.append(np.concatenate([loop, loop]))+ height.append(np.repeat([z0, z1], n))+ a = np.arange(n)+ b = (a + 1) % n+ wall = np.vstack([np.stack([a, b, n + b], 1), np.stack([a, n + b, n + a], 1)])+ faces.append(count + wall)+ count += 2 * n+ return np.concatenate(source), np.concatenate(height), np.vstack(faces)+++def fan(center: int, rim: np.ndarray) -> np.ndarray:+ return np.stack([np.full(len(rim) - 1, center), rim[:-1], rim[1:]], 1)+++def strip(inner: np.ndarray, outer: np.ndarray) -> np.ndarray:+ """Triangles between two closed rows of vertex indices of equal length."""+ a, b, c, d = inner, np.roll(inner, -1), np.roll(outer, -1), outer+ return np.vstack([np.stack([a, b, c], 1), np.stack([a, c, d], 1)])+++def facing_up(points: np.ndarray, tris: np.ndarray) -> np.ndarray:+ """The triangles, each wound counterclockwise seen from above (so the shading's averaged+ normals agree)."""+ a, b, c = points[tris[:, 0]], points[tris[:, 1]], points[tris[:, 2]]+ area = (b - a)[:, 0] * (c - a)[:, 1] - (b - a)[:, 1] * (c - a)[:, 0]+ return np.where((area < 0)[:, None], tris[:, ::-1], tris)+++def flexspline_face(cell: np.ndarray) -> Face:+ """The flexspline's top face in material terms, per vertex (tooth, x, y) in the tooth's own+ frame: per tooth its contour (13 points), the middle of its base and 4 points on the rim's+ inner edge. Returns them, the triangles and the boundary loops (toothed and inner).+ """+ contour = cell[:-1] # the next tooth's first point closes this one's root+ inner = np.column_stack(+ [[contour[0, 0], contour[1, 0], 0.0, contour[12, 0]], [-HF - RIM] * 4]+ )+ local = np.vstack([contour, [[0.0, -HF]], inner]) # 13 + 1 + 4 = 18 per tooth+ first = len(local) * np.arange(NF)[:, None]+ teeth = np.vstack([fan(j + 13, j + np.arange(1, 13)) for j in first[:, 0]])+ rows = [+ (first + np.array(k)[None]).ravel() for k in ([14, 15, 16, 17], [0, 1, 13, 12])+ ]+ material = np.column_stack(+ [np.repeat(np.arange(NF), len(local)), np.tile(local, (NF, 1))]+ )+ loops = [(first + np.arange(13)[None]).ravel(), rows[0]]+ return material, np.vstack([teeth, strip(*rows)]), loops+++def spline_face(radii: np.ndarray, half: np.ndarray) -> Face:+ """The circular spline's top face: 62 teeth pointing in (tooth k centred at (k + ½)·Δ) on a+ rim out to R_OUT. Returns points, triangles and boundary loops (toothed, outer)."""+ root = radii[-1] + CLEAR # the root circle, just beyond the flexspline's reach+ # the tooth's edge: root → tip → root+ edge_r = np.concatenate([[root], radii[::-1], radii[1:], [root]])+ edge_a = np.concatenate([[-half[-1]], -half[::-1], half[1:], [half[-1]]])+ n = len(edge_r)+ pts = []+ for k in range(NC):+ c = (k + 0.5) * DELTA+ pts.append(polar(edge_r, c + edge_a))+ pts.append(polar(np.full(2, root), c + np.array([0, DELTA / 2]))) # base, gap+ outside = c + np.array([-half[-1], 0, half[-1], DELTA / 2])+ pts.append(polar(np.full(4, R_OUT), outside))+ first = (n + 6) * np.arange(NC)[:, None]+ teeth = np.vstack([fan(j + n, j + np.arange(n)) for j in first[:, 0]])+ inner = (first + np.array([0, n, n - 1, n + 1])[None]).ravel()+ outer = (first + np.arange(n + 2, n + 6)[None]).ravel()+ points = np.vstack(pts)+ toothed = (first + np.append(np.arange(n), n + 1)[None]).ravel()+ return (+ points,+ facing_up(points, np.vstack([teeth, strip(inner, outer)])),+ [toothed, outer],+ )+++def plug_face(samples: int = 240) -> Face:+ """The wave generator's elliptical cam (in its own frame, long axis along x) around a hub."""+ spot, _, normal = pitch_line(np.linspace(0, m.TAU, samples, endpoint=False), W0)+ rim = spot + CAM * normal+ hub = HUB * rim / np.linalg.norm(rim, axis=1, keepdims=True)+ points = np.vstack([hub, rim])+ rows = np.arange(samples), samples + np.arange(samples)+ return points, facing_up(points, strip(*rows)), [rows[1], rows[0]]+++def flat(outline: np.ndarray, center: tuple[float, float]) -> Face:+ """A flat polygon, fanned from a point that sees its whole outline."""+ points = np.vstack([outline, [center]])+ tris = fan(len(outline), np.append(np.arange(len(outline)), 0))+ return points, facing_up(points, tris), [np.arange(len(outline))]+++def disk(radius: float) -> Face:+ return flat(+ polar(np.full(48, radius), np.linspace(0, m.TAU, 48, endpoint=False)), (0, 0)+ )+++def arrow(start: float, stop: float, w: float) -> Face:+ """A flat arrow along +x."""+ neck = stop - 3 * w+ half = [[start, -w / 2], [neck, -w / 2], [neck, -1.5 * w], [stop, 0]]+ return flat(np.array(half + [[x, -y] for x, y in half[-2::-1]]), (neck, 0))+++def ball() -> tuple[np.ndarray, np.ndarray]:+ """A bearing ball: a small sphere's vertices and triangles (a 6 × 10 grid)."""+ u, v = np.meshgrid(+ np.linspace(0, np.pi, 7), np.linspace(0, m.TAU, 11), indexing="ij"+ )+ grid = np.stack([np.sin(u) * np.cos(v), np.sin(u) * np.sin(v), np.cos(u)], -1)+ a = (np.arange(6)[:, None] * 11 + np.arange(10)[None]).ravel()+ tris = np.vstack(+ [np.stack([a, a + 11, a + 12], 1), np.stack([a, a + 12, a + 1], 1)]+ )+ return BALL * grid.reshape(-1, 3), tris+++def speed_profile() -> tuple[np.ndarray, np.ndarray]:+ """Times, and the plug's angle (turns) by then: the integral of the eased SPEED profile."""+ fine = np.linspace(0, SPEED[-1][0], 60001)+ speed = np.zeros_like(fine)+ for (t0, s0), (t1, s1) in pairwise(SPEED):+ x = np.clip((fine - t0) / (t1 - t0), 0, 1)+ inside = (fine >= t0) & (fine <= t1)+ speed[inside] = s0 + (s1 - s0) * (x * x * (3 - 2 * x))[inside]+ steps = (speed[1:] + speed[:-1]) / 2 * np.diff(fine)+ return fine, np.concatenate([[0], np.cumsum(steps)])+++PROFILE = speed_profile()+++def plug_turns(times: np.ndarray) -> np.ndarray:+ return np.interp(times, *PROFILE)+++def project(camera: m.Camera, point: np.ndarray) -> np.ndarray:+ """Where a 3D point lands on the screen, in frame coordinates (for HUD labels)."""+ turned = camera_axes(camera.get_phi(), camera.get_theta(), camera.get_gamma())+ p = turned @ (point - camera.frame_center)+ depth = 1 - p[2] / camera.get_focal_distance()+ return np.array([*(camera.get_zoom() * p[:2] / depth), 0.0])+++def rgba(color: str) -> np.ndarray:+ return np.array([*m.ManimColor(color).to_rgb(), 1.0])+++def live(+ value: Callable[[], float], places: int, shown: m.ValueTracker, right: np.ndarray+) -> m.DecimalNumber:+ """A number that follows `value` every frame, its right edge at `right`, faded by a tracker+ (it is rebuilt each frame, so it must not be faded by an animation)."""+ number = m.DecimalNumber(value(), num_decimal_places=places, font_size=30)++ def refresh(mob: m.DecimalNumber) -> None:+ mob.set_value(value()).set_opacity(shown.get_value())+ mob.move_to(right, aligned_edge=m.RIGHT)++ number.add_updater(refresh)+ refresh(number)+ return number+++class HarmonicDrive(m.ThreeDScene):+ def construct(self) -> None:+ self.camera.background_color = "#0f1318"+ cell = tooth_cell()+ radii, half = spline_tooth(cell)+ # the red tooth is the one at the long axis in the middle of the close-up; the whole+ # drive is turned so that it starts at 12 o'clock+ close_up = plug_turns(np.array([CLOSE_UP]))[0] * m.TAU+ red = round(close_up * NC / m.TAU) % NF+ start = place_teeth(np.zeros((1, 2)), 0.0, W0)[red, 0]+ zero = np.pi / 2 - np.arctan2(start[1], start[0])+ clock = [0.0]+ bulge = m.ValueTracker(0.0) # the flexspline's bulge, in units of W0+ lift = {"plug": m.ValueTracker(3.8), "flex": m.ValueTracker(1.9)}+ seen = {"psi": 0.0, "beta": 0.0} # plug and ring angles, as drawn this frame++ def psi() -> float:+ return float(plug_turns(np.array([clock[0]]))[0] * m.TAU)++ def place(xy: np.ndarray, z: np.ndarray, angle: float = 0.0) -> np.ndarray:+ return np.column_stack([turn(xy, angle + zero), z])++ # circular spline: fixed+ face, tris, loops = spline_face(radii, half)+ source, height, faces = prism(face, tris, loops, 0.0, 0.5)+ spline = m.MeshMobject(+ place(face[source], height), faces, shade_in_3d=True, fill_color=STEEL+ )++ # flexspline: 60 rigid teeth riding the flexed pitch line, colored by how far the plug+ # pushes each out (bright) or pulls it in (dim): the strain wave+ material, tris, loops = flexspline_face(cell)+ f_source, f_height, f_faces = prism(material[:, 1:], tris, loops, 0.02, 0.56)+ tooth_of = material[f_source, 0].astype(int)+ local = material[f_source, 1:]+ dim, gold, bright = rgba("#5e4418"), rgba(BRASS), rgba("#fff6d0")+ rest = m.TAU * np.arange(NF) / NF++ def flex_update(mob: m.MeshMobject) -> None:+ a, w = psi(), bulge.get_value()+ theta = rest - a * NC / NF+ spot, tangent, normal = pitch_line(theta, W0 * w)+ xy = spot[tooth_of] + local[:, :1] * tangent[tooth_of]+ xy += local[:, 1:] * normal[tooth_of]+ mob.points = place(xy, f_height + lift["flex"].get_value(), a)+ # the ring's turn, measured from the drawn teeth: their mean angle from rest+ moved = turn(spot, a)+ angles = np.arctan2(moved[:, 1], moved[:, 0]) - rest+ seen["psi"], seen["beta"] = a, float(np.angle(np.exp(1j * angles).mean()))+ strain = w * np.cos(2 * theta)[tooth_of, None]+ rows = np.where(+ strain > 0,+ gold + strain * (bright - gold),+ gold - strain * (dim - gold),+ )+ rows[tooth_of == red] = rgba(RED)+ mob.paint = mob.paint.but(fill=rows)++ flex = m.MeshMobject(np.zeros((len(f_source), 3)), f_faces, shade_in_3d=True)+ flex_update(flex)+ flex.add_updater(flex_update)++ # wave generator: the cam, its hub and an arrow along its long axis, and the balls+ parts = [plug_face(), disk(HUB), arrow(HUB + 0.12, RP + W0 + CAM - 0.12, 0.07)]+ levels = [(0.08, 0.46), (0.0, 0.74), (0.46, 0.47)]+ tints = [PLUG, "#c9ced6", "#f1faee"]+ plug_parts = []+ for (face, tris, loops), (z0, z1), tint in zip(parts, levels, tints):+ source, height, faces = prism(face, tris, loops, z0, z1)+ mesh = m.MeshMobject(+ place(face[source], height), faces, shade_in_3d=True, fill_color=tint+ )++ def pose(+ mob: m.Mobject, xy: np.ndarray = face[source], z: np.ndarray = height+ ) -> None:+ mob.points = place(xy, z + lift["plug"].get_value(), psi())++ mesh.add_updater(pose)+ plug_parts.append(mesh)+ sphere, one = ball()+ tris = np.vstack([one + k * len(sphere) for k in range(BALLS)])+ balls = m.MeshMobject(+ np.zeros((BALLS * len(sphere), 3)),+ tris,+ shade_in_3d=True,+ fill_color="#e8ecf2",+ )++ def roll(mob: m.Mobject) -> None:+ a = psi()+ cage = (+ m.TAU * np.arange(BALLS) / BALLS - 0.52 * a+ ) # the cage: about half speed+ spot, _, normal = pitch_line(cage, W0)+ z = np.full(BALLS, 0.27 + lift["plug"].get_value())+ centers = place(spot + (CAM + BALL) * normal, z, a)+ mob.points = (centers[:, None] + sphere[None]).reshape(-1, 3)++ balls.add_updater(roll)+ roll(balls)++ # on the fixed ring, a tick grows where the ring has got to after each whole turn of+ # the plug: two teeth (12°) apart+ grid = np.linspace(0, SPEED[-1][0], 3101)+ turns = np.arange(int(plug_turns(grid)[-1]) + 1)+ when = np.interp(turns, plug_turns(grid), grid)+ when[0] = SPEED[1][0] # where the red tooth starts+ root = radii[-1] + CLEAR+ across = np.array([-0.028, 0.028, 0.028, -0.028])+ quad = np.array([[0, 1, 2], [0, 2, 3]])+ tick_tris = np.vstack([quad + 4 * k for k in range(len(turns))])++ def tick_points() -> np.ndarray:+ grow = np.clip((clock[0] - when) / 0.5, 0, 1)+ out = []+ for k, g in zip(turns, grow):+ r = root + 0.07 + np.array([0, 0, 0.3, 0.3]) * max(g, 1e-3)+ out.append(+ turn(np.column_stack([r, across]), np.pi / 2 - k * m.TAU / 30)+ )+ xy = np.vstack(out)+ return np.column_stack([xy, np.full(len(xy), 0.504)])++ ticks = m.MeshMobject(+ tick_points(), tick_tris, shade_in_3d=True, fill_color=m.WHITE+ )+ ticks.add_updater(lambda mob: setattr(mob, "points", tick_points()))++ def advance(mob: m.Mobject, dt: float) -> None:+ clock[0] += dt++ driver = m.Mobject().add_updater(advance)++ # heads-up display+ title = m.Text("Strain-wave gearing", font_size=38).to_corner(m.UL)+ notes = [+ "an elliptical plug flexes a 60-tooth ring inside a 62-tooth ring",+ "the ring meshes only where the plug pushes it out",+ (+ "where the ring bulges, its teeth sink into the gaps; a quarter turn"+ " on, they clear"+ ),+ ]+ subtitles = [m.Text(t, font_size=22).set_color(m.GREY_B) for t in notes]+ for sub in subtitles:+ sub.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ labels = m.VGroup()+ for name, note, color in [+ ("wave generator", "input: an elliptical plug", PLUG_LIGHT),+ ("flexspline", "60 teeth: output", BRASS),+ ("circular spline", "62 teeth: fixed", "#aab4c3"),+ ]:+ labels.add(+ m.VGroup(+ m.Text(name, font_size=26).set_color(color),+ m.Text(note, font_size=20).set_color(m.GREY_B),+ ).arrange(m.DOWN, aligned_edge=m.RIGHT, buff=0.1)+ )+ reaches = [RP + W0 + CAM + 2 * BALL, RP + HA, R_OUT]+ around = polar(np.ones(72), np.linspace(0, m.TAU, 72, endpoint=False))++ def follow(group: m.Mobject) -> None:+ """Each label just left of its part, never closer than 0.95 to the one below."""+ floor = -np.inf+ parts = zip(group[::-1], ["spline", "flex", "plug"], reaches[::-1])+ for label, part, reach in parts:+ z = 0.3 + (lift[part].get_value() if part in lift else 0.0)+ rim = [+ project(self.camera, np.array([*(reach * p), z])) for p in around+ ]+ spot = min(rim, key=lambda q: q[0])+ y = max(spot[1], floor + 0.95)+ label.move_to([spot[0] - 0.3 - label.width / 2, y, 0])+ floor = y++ labels.add_updater(follow)++ formula = m.MathTex(+ r"\beta = -\frac{N_c - N_f}{N_f}\,\psi = -\frac{\psi}{30}", font_size=34+ )+ shown = m.ValueTracker(0.0)+ rows_y = [0.3 - 0.62 * k for k in range(3)]+ readings: list[tuple[Callable[[], float], int]] = [+ (lambda: seen["psi"] / m.TAU, 2), # plug turns+ (lambda: seen["beta"] / m.TAU * NF, 1), # ring teeth+ (lambda: seen["psi"] / seen["beta"] if seen["psi"] > 0.5 else -30.0, 1),+ ]+ numbers = [+ live(value, places, shown, np.array([-2.35, y, 0]))+ for (value, places), y in zip(readings, rows_y)+ ]+ names = [+ m.MathTex(r"\text{wave generator}\;\psi", font_size=30),+ m.MathTex(r"\text{flexspline}\;\beta", font_size=30),+ m.MathTex(r"\psi / \beta", font_size=30),+ ]+ units = [m.Text(u, font_size=24) for u in ("turns", "teeth", ": 1")]+ for name, unit, y in zip(names, units, rows_y):+ name.move_to([-6.75, y, 0], aligned_edge=m.LEFT)+ unit.move_to([-2.2, y - 0.02, 0], aligned_edge=m.LEFT)+ formula.move_to([-6.75, 1.55, 0], aligned_edge=m.LEFT)+ statics = m.VGroup(formula, *names, *units)+ closing = m.VGroup(+ m.Text("62 − 60 = 2 teeth:", font_size=28),+ m.Text("one turn in, two teeth back", font_size=28),+ m.Text("30 : 1 in one flat stage, without backlash", font_size=22),+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.14)+ closing[2].set_color(m.GREY_B)+ closing.move_to([-6.75, -2.75, 0], aligned_edge=m.LEFT)+ self.add_fixed_in_frame_mobjects(+ title, *subtitles, labels, statics, *numbers, closing+ )+ self.remove(*subtitles, labels, statics, closing)++ def main_view(run_time: float) -> None:+ """Looking down at 32° on the drive, at the right of the frame (the HUD's left)."""+ self.move_camera(+ phi=32 * m.DEGREES,+ theta=-90 * m.DEGREES,+ zoom=0.92,+ frame_center=[-3.35, 0.2, 0],+ run_time=run_time,+ )++ # 0–6.5 s: the parts, apart; then assembled: the plug flexes the ring as it goes in+ self.add(driver, spline, flex, *plug_parts, balls, ticks)+ self.set_camera_orientation(+ phi=63 * m.DEGREES,+ theta=-78 * m.DEGREES,+ zoom=0.86,+ frame_center=[-0.6, 0, 2.25],+ )+ self.begin_ambient_camera_rotation(rate=0.05)+ self.play(m.FadeIn(subtitles[0]), m.FadeIn(labels), run_time=1.2)+ self.wait(1.6)+ self.play(+ lift["plug"].animate.set_value(1.9),+ bulge.animate.set_value(1.0),+ m.FadeOut(labels, run_time=0.8),+ run_time=1.9,+ )+ self.play(+ lift["plug"].animate.set_value(0.0),+ lift["flex"].animate.set_value(0.0),+ run_time=1.7,+ )+ self.stop_ambient_camera_rotation()+ # 6.5–19 s: the plug spins; the ring creeps back the other way, two teeth a turn+ self.play(m.FadeOut(subtitles[0]), run_time=0.4)+ main_view(2.0)+ self.play(+ m.FadeIn(subtitles[1]),+ m.FadeIn(statics),+ shown.animate.set_value(1.0),+ run_time=1.0,+ )+ self.wait(SPEED[3][0] - self.time)+ # 19–27 s: close up on the mesh where the long axis passes the red tooth+ axis = close_up + zero+ spot = np.array([3.2 * np.cos(axis), 3.2 * np.sin(axis), 0.5])+ view = (+ axis + np.pi / 2+ ) % m.TAU - 1.5 * np.pi # axis − π, the turn nearest −π/2+ self.play(+ m.FadeOut(statics),+ shown.animate.set_value(0.0),+ m.FadeOut(subtitles[1]),+ run_time=0.5,+ )+ self.move_camera(+ phi=16 * m.DEGREES, theta=view, zoom=2.3, frame_center=spot, run_time=1.8+ )+ self.play(m.FadeIn(subtitles[2]), run_time=0.6)+ self.wait(SPEED[5][0] - self.time - 0.5)+ self.play(m.FadeOut(subtitles[2]), run_time=0.5)+ main_view(1.8)+ # 27–30.5 s: the poster+ self.play(+ m.FadeIn(statics),+ shown.animate.set_value(1.0),+ m.FadeIn(subtitles[1]),+ m.FadeIn(closing, shift=0.15 * m.UP),+ run_time=1.0,+ )+ self.wait(30.5 - self.time)+++if __name__ == "__main__":+ HarmonicDrive().render("harmonic_drive.mp4")diff --git a/examples/phased_array.py b/examples/phased_array.pynew file mode 100644index 00000000..2b31b432--- /dev/null+++ b/examples/phased_array.py@@ -0,0 +1,558 @@+"""Steering a beam with phase alone: a phased array.++Eight identical antennas that never move send out the same wave, each one a constant phase step+Δφ behind its neighbour. Their waves add up to a beam whose direction obeys sin θ = Δφ λ/(2π d),+the principle of every phased-array radar and 5G base station. The field is summed live from the+eight sources; the beam angle is measured from the array factor |Σ e^{ij(Δφ − kd sin θ)}| and set+beside the law. At twice the frequency (d = λ) a second, grating lobe appears. An 8×8 array steers+a 3D pencil beam the same way, with a phase step along each side.+"""++import numpy as np++import manimgx as m++N = 8 # antennas per row+WAVELENGTH = 0.6+PITCH = WAVELENGTH / 2 # d, fixed: the antennas never move+FREQUENCY = 1.1 # wave cycles per second+RADIUS = 5.0 # of the half-disc of field above the array+PIXELS = (800, 400)+ROW_Y = -PITCH / 2 # the field is drawn in the plane of one row of the planar array+LOBE = 3.6 # length of the 3D beam at full gain+FIELD = [+ (-1.0, "#c8f4ff"),+ (-0.55, "#2c93d8"),+ (-0.18, "#0a2240"),+ (0.0, "#04060b"),+ (0.18, "#3d1f06"),+ (0.55, "#e38a2b"),+ (1.0, "#fff2cc"),+]+GOLD = "#f0c05a"+GAIN = ["#0d2b52", "#1768ac", "#2fb5c9", "#f2d479", "#fff7e0"]+++def colormap(values: np.ndarray, stops: list[str]) -> np.ndarray:+ """(n, 4) RGBA rows for values in [0, 1], interpolated through color stops."""+ rgb = np.array([m.ManimColor(s).to_rgb() for s in stops])+ x = np.clip(values, 0, 1) * (len(stops) - 1)+ i = np.minimum(x.astype(int), len(stops) - 2)+ f = (x - i)[:, None]+ out = np.ones((len(values), 4))+ out[:, :3] = rgb[i] * (1 - f) + rgb[i + 1] * f+ return out+++def field_palette() -> np.ndarray:+ """A 256-entry RGBA lookup table for field values in [−1, 1]."""+ at = np.array([v for v, _ in FIELD])+ rgb = np.array([m.ManimColor(c).to_rgb() for _, c in FIELD])+ x = np.linspace(-1, 1, 256)+ table = np.stack([np.interp(x, at, rgb[:, c]) for c in range(3)], axis=1)+ return np.column_stack([table * 255, np.full(256, 255)]).astype(np.uint8)+++def grid_mesh(points: np.ndarray, fill_color: str) -> m.MeshMobject:+ """A smooth lit mesh over an (nu+1, nv+1, 3) grid of points computed with numpy (vertex+ i·(nv + 1) + j), each cell two triangles."""+ nu, nv = points.shape[0] - 1, points.shape[1] - 1+ idx = np.arange((nu + 1) * (nv + 1)).reshape(nu + 1, nv + 1)+ a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]+ cells = np.stack([np.stack([a, b, c], -1), np.stack([a, c, d], -1)], 2)+ return m.MeshMobject(+ points.reshape(-1, 3),+ cells.reshape(-1, 3),+ shade_in_3d=True,+ fill_color=fill_color,+ )+++def array_factor(u: np.ndarray, step: float, kd: float) -> np.ndarray:+ """|Σ_j e^{ij(step − kd u)}| / N for direction cosines u along a row of N antennas, summed+ in closed form: |sin(Nψ/2) / (N sin(ψ/2))| with ψ = step − kd u."""+ half = (step - kd * u) / 2+ below = np.sin(half)+ tiny = np.abs(below) < 1e-9+ return np.abs(+ np.where(tiny, 1.0, np.sin(N * half) / (N * np.where(tiny, 1.0, below)))+ )+++SCAN = np.radians(np.linspace(-90, 90, 3601))+_found: dict[tuple[float, float], list[float]] = {}+++def lobes(step: float, kd: float) -> list[float]:+ """Measured beam directions (degrees from broadside): the peaks of the array factor."""+ if (step, kd) not in _found:+ a = array_factor(np.sin(SCAN), step, kd)+ peak = (a > 0.8) & (a >= np.roll(a, 1)) & (a >= np.roll(a, -1))+ peak[[0, -1]] = a[[0, -1]] > 0.8+ _found.clear()+ _found[step, kd] = [float(np.degrees(t)) for t in SCAN[peak]]+ return _found[step, kd]+++class Array:+ """The live state: phase step(s), frequency, time; the field over the half-disc."""++ def __init__(self) -> None:+ self.time = 0.0+ self.step = m.ValueTracker(0.0) # Δφ along x (radians)+ self.step_y = m.ValueTracker(0.0) # Δφ along y (the planar array)+ self.octave = m.ValueTracker(1.0) # frequency multiplier+ w, h = PIXELS+ xs = np.linspace(-RADIUS, RADIUS, w)+ zs = np.linspace(RADIUS, 0, h)+ self.x, self.z = np.meshgrid(xs, zs)+ rim = np.hypot(self.x, self.z)+ edge = np.clip((RADIUS - rim) / (0.12 * RADIUS), 0, 1)+ self.edge = (edge**1.5).ravel()+ self.compensate = (np.sqrt(rim + 0.6) / N).astype(np.float32).ravel()+ self.sources = (np.arange(N) - (N - 1) / 2) * PITCH+ # each source's distance to every pixel, and its 1/√r fall-off+ r = np.hypot(self.x[None] - self.sources[:, None, None], self.z[None])+ self.r = r.reshape(N, -1).astype(np.float32)+ self.falloff = (1 / np.sqrt(self.r + 0.03)).astype(np.float32)+ self.palette = (+ field_palette().view(np.uint32).ravel()+ ) # one RGBA word per entry+ self.basis_octave = -1.0+ self.basis = np.zeros((N, w * h), np.complex64)++ @property+ def k(self) -> float:+ return 2 * np.pi * self.octave.get_value() / WAVELENGTH++ def phases(self) -> np.ndarray:+ """Each antenna's drive phase now: j Δφ − ωt."""+ omega = 2 * np.pi * FREQUENCY * self.octave.get_value()+ return np.arange(N) * self.step.get_value() - omega * self.time++ def picture(self, shown: float = 1.0) -> np.ndarray:+ """Re Σ_j e^{i(k r_j + jΔφ − ωt)} / √r_j over the half-disc, as RGBA pixels."""+ if self.basis_octave != self.octave.get_value():+ kr = np.float32(self.k) * self.r+ self.basis = (self.falloff * np.cos(kr)) + 1j * (self.falloff * np.sin(kr))+ self.basis = self.basis.astype(np.complex64)+ self.basis_octave = self.octave.get_value()+ drive = np.exp(1j * self.phases()).astype(np.complex64)+ value = (drive @ self.basis).real * self.compensate+ index = np.clip((value + 1) * 127.5, 0, 255).astype(np.uint8)+ rgba = self.palette[index].view(np.uint8).reshape(*self.x.shape, 4)+ rgba[..., 3] = (255 * shown * self.edge).astype(np.uint8).reshape(self.x.shape)+ return rgba+++class PhasedArray(m.ThreeDScene):+ def construct(self) -> None:+ self.set_camera_orientation(+ phi=90 * m.DEGREES,+ theta=-90 * m.DEGREES,+ zoom=0.92,+ frame_center=np.array([1.74, 0, 2.95]),+ )+ state = Array()+ clock = m.ValueTracker(0.0)++ def tick(_: m.Mobject, dt: float) -> None:+ state.time += dt++ clock.add_updater(tick)+ shown = m.ValueTracker(1.0) # the field's visibility++ # ── the field, a textured half-disc standing in the plane of the array ──────────────+ field = m.ImageMobject(state.picture())+ field.scale_to_fit_width(2 * RADIUS)+ field.rotate(90 * m.DEGREES, axis=m.RIGHT)+ field.move_to(np.array([0, ROW_Y, RADIUS / 2]))++ def paint_field(mob: m.Mobject) -> None:+ mob.paint = mob.paint.but(texture=state.picture(shown.get_value()))++ field.add_updater(paint_field)++ # ── the antennas, pulsing with their own phase, and a phasor dial under each ────────+ xs = state.sources+ antennas = m.VGroup(+ *[m.Dot3D(np.array([x, ROW_Y, 0]), radius=0.07) for x in xs]+ )++ antennas_on = m.ValueTracker(1.0)++ def pulse(group: m.Mobject) -> None:+ glow = (1 + np.cos(state.phases())) / 2+ dim, bright = m.ManimColor("#6b4a1f"), m.ManimColor("#ffe7a8")+ for dot, g in zip(group.submobjects, glow, strict=True):+ dot.set_color(m.interpolate_color(dim, bright, g))+ dot.set_opacity(antennas_on.get_value())++ antennas.add_updater(pulse)+ dials_on = m.ValueTracker(1.0)++ def dials() -> m.VGroup:+ group = m.VGroup()+ for x, phase in zip(xs, state.phases(), strict=True):+ center = np.array([x, ROW_Y, -0.45])+ hand = 0.12 * np.array([np.cos(phase), 0, np.sin(phase)])+ group.add(+ m.Circle(radius=0.13, stroke_width=1.5, color=m.GREY_B)+ .rotate(90 * m.DEGREES, axis=m.RIGHT)+ .move_to(center),+ m.Line(center, center + hand, stroke_width=2.5, color="#ffe7a8"),+ )+ return group.set_stroke(opacity=dials_on.get_value())++ dial_group = m.always_redraw(dials)++ # ── heads-up display ─────────────────────────────────────────────────────────────────+ title = m.Text("Steering a beam with phase alone", font_size=36).to_corner(m.UL)+ subtitle = m.Text(+ "eight fixed antennas, each a phase step Δφ behind the last", font_size=22+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ law = m.MathTex(+ r"\sin\theta = \frac{\Delta\phi\,\lambda}{2\pi d}", font_size=38+ )+ law.to_corner(m.UR).shift(0.15 * m.LEFT)++ # polar plot of the array factor: angle from broadside, radius = |AF|+ hub = np.array([5.05, 0.35, 0])+ size = 1.55+ polar = m.VGroup(+ m.Arc(radius=size, start_angle=0, angle=np.pi, arc_center=hub),+ m.Arc(radius=size / 2, start_angle=0, angle=np.pi, arc_center=hub),+ m.Line(hub - size * m.RIGHT, hub + size * m.RIGHT),+ *[+ m.Line(hub, hub + size * np.array([np.sin(a), np.cos(a), 0]))+ for a in np.radians([-60, -30, 0, 30, 60])+ ],+ ).set_stroke(m.GREY_D, 1.2)+ ticks = m.VGroup(+ *[+ m.MathTex(rf"{a}^\circ", font_size=20)+ .set_color(m.GREY_B)+ .move_to(+ hub+ + (size + 0.25)+ * np.array([np.sin(np.radians(a)), np.cos(np.radians(a)), 0])+ )+ for a in (-60, 0, 60)+ ]+ )+ angles = np.radians(np.linspace(-90, 90, 721))++ def pattern() -> m.VGroup:+ kd = state.k * PITCH+ a = array_factor(np.sin(angles), state.step.get_value(), kd)+ curve = m.VMobject(stroke_color=GOLD, stroke_width=2.5)+ curve.set_points_as_corners(+ hub+ + size+ * a[:, None]+ * np.stack([np.sin(angles), np.cos(angles), 0 * angles], 1)+ )+ beams = m.VGroup(+ *[+ m.Line(+ hub,+ hub+ + size+ * np.array([np.sin(np.radians(b)), np.cos(np.radians(b)), 0]),+ stroke_width=1.5,+ color=m.WHITE,+ )+ for b in lobes(state.step.get_value(), kd)+ ]+ )+ return m.VGroup(curve, beams)++ pattern_on = m.ValueTracker(0.0)+ polar_curve = m.always_redraw(+ lambda: pattern().set_stroke(opacity=pattern_on.get_value())+ )++ def readout(tex: str, *values: m.Mobject) -> m.VGroup:+ return m.VGroup(m.MathTex(tex, font_size=30), *values).arrange(+ m.RIGHT, buff=0.15+ )++ def number(+ places: int, unit: str | None = None, color: str = "#ffffff"+ ) -> m.DecimalNumber:+ return m.DecimalNumber(+ 0, num_decimal_places=places, font_size=30, unit=unit, color=color+ )++ step_value = number(2, r"\pi")+ step_value.add_updater(lambda d: d.set_value(state.step.get_value() / np.pi))+ spacing_value = number(2)+ spacing_value.add_updater(lambda d: d.set_value(PITCH * state.k / (2 * np.pi)))+ # the measured beams: the main one (nearest the law's) and a grating lobe, if any+ main_value = number(1, r"^\circ", color=GOLD)+ second_value = number(1, r"^\circ", color=GOLD)+ comma = m.MathTex(",", font_size=30, color=GOLD)+ law_value = number(1, r"^\circ")++ def principal() -> float:+ s = state.step.get_value() / (state.k * PITCH)+ return float(np.degrees(np.arcsin(np.clip(s, -1, 1))))++ def measure_beams(_: m.Mobject) -> None:+ found = sorted(+ lobes(state.step.get_value(), state.k * PITCH),+ key=lambda b: abs(b - principal()),+ )+ main_value.set_value(found[0])+ second_value.set_value(found[1] if len(found) > 1 else 0)+ second_value.set_opacity(1 if len(found) > 1 else 0)+ comma.set_opacity(1 if len(found) > 1 else 0)+ law_value.set_value(principal())++ law_value.add_updater(measure_beams)+ rows = m.VGroup(+ readout(r"\Delta\phi =", step_value),+ readout(r"d/\lambda =", spacing_value),+ readout(r"\theta_{\text{beam}} =", main_value, comma, second_value),+ readout(r"\arcsin\tfrac{\Delta\phi\,\lambda}{2\pi d} =", law_value),+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2)+ rows[2][2].shift(0.1 * m.LEFT + 0.08 * m.DOWN)+ rows.next_to(hub + size * m.DOWN, m.DOWN, buff=0.15).align_to(+ hub + (size + 0.25) * m.LEFT, m.LEFT+ )+ hud_1d = m.VGroup(polar, ticks, rows)++ # ── the planar array: 8×8 patches, each lit by its phase ─────────────────────────────+ grid = (np.arange(N) - (N - 1) / 2) * PITCH+ gx, gy = np.meshgrid(grid, grid, indexing="ij")+ centers = np.column_stack([gx.ravel(), gy.ravel(), np.full(N * N, 0.01)])+ half = 0.1+ corners = np.array(+ [[-half, -half, 0], [half, -half, 0], [half, half, 0], [-half, half, 0]]+ )+ verts = (centers[:, None, :] + corners[None]).reshape(-1, 3)+ base = 4 * np.arange(N * N)[:, None]+ tris = np.concatenate([base + [0, 1, 2], base + [0, 2, 3]])+ patches = m.MeshMobject(verts, tris, fill_color="#ffe7a8")+ board = m.Prism(+ dimensions=[N * PITCH + 0.3, N * PITCH + 0.3, 0.06], fill_color="#1a2230"+ )+ board.move_to(np.array([0, 0, -0.035]))+ planar_on = m.ValueTracker(0.0)++ def light_patches(mob: m.Mobject) -> None:+ omega = 2 * np.pi * FREQUENCY * state.octave.get_value()+ phase = (+ gx.ravel() / PITCH * state.step.get_value()+ + gy.ravel() / PITCH * state.step_y.get_value()+ - omega * state.time+ )+ rows_ = colormap((1 + np.cos(phase)) / 2, ["#3a2a12", "#ffe7a8"])+ rows_[:, 3] = planar_on.get_value()+ mob.paint = mob.paint.but(fill=np.repeat(rows_, 4, axis=0))++ patches.add_updater(light_patches)++ # ── the 3D beam: |AF_x · AF_y| over the upper hemisphere, as a lit surface ──────────+ th = np.linspace(0, np.pi / 2, 121)+ ph = np.linspace(0, 2 * np.pi, 181)+ tt, pp = np.meshgrid(th, ph, indexing="ij")+ dirs = np.stack(+ [np.sin(tt) * np.cos(pp), np.sin(tt) * np.sin(pp), np.cos(tt)], -1+ )+ grow = m.ValueTracker(0.0)++ def gain(d: np.ndarray) -> np.ndarray:+ kd = state.k * PITCH+ return array_factor(d[..., 0], state.step.get_value(), kd) * array_factor(+ d[..., 1], state.step_y.get_value(), kd+ )++ lobe = grid_mesh(dirs * 0.01, fill_color=GAIN[2])++ def shape_lobe(mob: m.Mobject) -> None:+ g = gain(dirs)+ mob.points = (+ LOBE * grow.get_value() * g[..., None] * dirs + 1e-3 * dirs+ ).reshape(-1, 3)+ mob.paint = mob.paint.but(fill=colormap(g.ravel(), GAIN))++ lobe.add_updater(shape_lobe)++ beam = np.zeros(+ 2+ ) # the measured beam direction (θ, φ in degrees), once a frame++ def peak(_: m.Mobject) -> None:+ """The maximum of |AF| over the hemisphere, refined on a fine patch around it."""+ g = gain(dirs)+ i, j = np.unravel_index(int(np.argmax(g)), g.shape)+ fine_t = np.linspace(th[max(i - 1, 0)], th[min(i + 1, len(th) - 1)], 41)+ fine_p = np.linspace(ph[j] - 0.05, ph[j] + 0.05, 41)+ ft, fp = np.meshgrid(fine_t, fine_p, indexing="ij")+ fd = np.stack(+ [np.sin(ft) * np.cos(fp), np.sin(ft) * np.sin(fp), np.cos(ft)], -1+ )+ k = np.unravel_index(int(np.argmax(gain(fd))), ft.shape)+ beam[:] = np.degrees(ft[k]), np.degrees(fp[k]) % 360++ axis_line = m.Line3D(np.zeros(3), m.OUT, thickness=0.012, color=m.WHITE)++ def point_axis(mob: m.Mobject) -> None:+ t, p = np.radians(beam)+ d = np.array([np.sin(t) * np.cos(p), np.sin(t) * np.sin(p), np.cos(t)])+ mob.become(+ m.Line3D(+ np.zeros(3),+ (LOBE + 0.6) * grow.get_value() * d + 1e-3 * d,+ thickness=0.012,+ color=m.WHITE,+ )+ )++ axis_line.add_updater(peak)+ axis_line.add_updater(point_axis)++ beam_t, beam_p = (+ number(1, r"^\circ", color=GOLD),+ number(0, r"^\circ", color=GOLD),+ )+ law_t, law_p = number(1, r"^\circ"), number(0, r"^\circ")++ def planar_law(_: m.Mobject) -> None:+ kd = state.k * PITCH+ u, v = state.step.get_value() / kd, state.step_y.get_value() / kd+ beam_t.set_value(beam[0])+ beam_p.set_value(beam[1])+ law_t.set_value(np.degrees(np.arcsin(min(1.0, float(np.hypot(u, v))))))+ law_p.set_value(np.degrees(np.arctan2(v, u)) % 360)++ law_p.add_updater(planar_law)++ def pair(name: str, t: m.Mobject, p: m.Mobject, color: str) -> m.VGroup:+ row = m.VGroup(+ m.Text(name, font_size=24).set_color(color),+ m.MathTex(r"\theta =", font_size=30),+ t,+ m.MathTex(r"\varphi =", font_size=30),+ p,+ ).arrange(m.RIGHT, buff=0.15)+ row[3:].shift(0.25 * m.RIGHT)+ return row++ hud_2d = m.VGroup(+ pair("beam", beam_t, beam_p, GOLD), pair("law", law_t, law_p, "#ffffff")+ ).arrange(m.DOWN, aligned_edge=m.LEFT, buff=0.2)+ hud_2d.to_corner(m.DR).shift(0.25 * m.UP)+ law_2d = (+ m.MathTex(+ r"\sin\theta\,(\cos\varphi,\ \sin\varphi) = \frac{\lambda}{2\pi"+ r" d}\,(\Delta\phi_x,\ \Delta\phi_y)",+ font_size=28,+ )+ .to_corner(m.UR)+ .shift(0.15 * m.LEFT + 0.1 * m.DOWN)+ )++ self.add(clock, field, antennas, dial_group)+ self.add_fixed_in_frame_mobjects(title, subtitle, law, hud_1d, polar_curve)+ self.remove(title, subtitle, law, hud_1d)++ # 0–3 s: in step, the waves add up straight ahead+ self.play(m.Write(title), m.FadeIn(subtitle), run_time=1.5)+ self.play(+ m.FadeIn(law),+ m.FadeIn(hud_1d),+ pattern_on.animate.set_value(1),+ run_time=1.2,+ )+ self.wait(0.4)+ # 3–11 s: a phase step between neighbours tilts the wavefronts and the beam+ self.play(state.step.animate.set_value(0.5 * np.pi), run_time=2.2)+ self.wait(0.5)+ self.play(state.step.animate.set_value(-0.7 * np.pi), run_time=3.0)+ self.wait(0.4)+ self.play(state.step.animate.set_value(0.25 * np.pi), run_time=1.5)+ # 11–15 s: the same antennas at twice the frequency: d = λ, and a second beam appears+ note = m.Text(+ "same antennas, twice the frequency: d = λ, and a second beam", font_size=22+ ).set_color(m.GREY_B)+ note.next_to(subtitle, m.DOWN, aligned_edge=m.LEFT, buff=0.2)+ self.add_fixed_in_frame_mobjects(note)+ self.remove(note)+ self.play(+ state.octave.animate.set_value(2.0),+ m.FadeIn(note, shift=0.1 * m.DOWN),+ run_time=2.5,+ )+ self.wait(1.5)+ self.play(state.octave.animate.set_value(1.0), m.FadeOut(note), run_time=1.5)++ # 16–20 s: the full 8×8 panel steers a pencil beam in 3D+ def first(+ t: float,+ ) -> float: # the old readouts leave in the first 40% of the move+ return m.smooth(min(1.0, t / 0.4))++ def last(t: float) -> float: # the new ones arrive in the last half+ return m.smooth(max(0.0, 2 * t - 1))++ self.add(board, patches, lobe, axis_line)+ peak(+ axis_line+ ) # the readouts hold still while they fade in: give them their values+ planar_law(law_p)+ self.add_fixed_in_frame_mobjects(law_2d, hud_2d)+ self.remove(law_2d, hud_2d)+ self.move_camera(+ phi=62 * m.DEGREES,+ theta=-58 * m.DEGREES,+ zoom=1.2,+ frame_center=np.array([0.2, 0, 1.95]),+ run_time=3.5,+ added_anims=[+ planar_on.animate.set_value(1),+ dials_on.animate.set_value(0),+ antennas_on.animate(rate_func=first).set_value(0),+ grow.animate.set_value(1),+ shown.animate.set_value(0),+ m.FadeOut(hud_1d, rate_func=first),+ pattern_on.animate(rate_func=first).set_value(0),+ m.FadeOut(law, rate_func=first),+ m.FadeIn(law_2d, rate_func=last),+ m.FadeIn(hud_2d, rate_func=last),+ ],+ )+ # 20–28 s: a conical scan: the step turns around the panel, the beam sweeps a cone+ self.begin_ambient_camera_rotation(rate=0.1)+ sweep = m.ValueTracker(0.0)+ tilt = 0.55 * np.pi++ def steer(_: m.Mobject) -> None:+ a = sweep.get_value()+ state.step.set_value(tilt * np.cos(a) * min(1.0, a / 0.6 + 0.45))+ state.step_y.set_value(tilt * np.sin(a) * min(1.0, a / 0.6 + 0.45))++ sweep.add_updater(steer)+ self.add(sweep)+ self.play(+ sweep.animate.set_value(2 * np.pi),+ run_time=7.0,+ rate_func=m.linear,+ )+ closing = m.Text("No moving parts: the phase steers the beam.", font_size=28)+ closing.to_edge(m.DOWN, buff=0.35).to_edge(m.LEFT, buff=0.5)+ self.add_fixed_in_frame_mobjects(closing)+ self.remove(closing)+ self.play(+ m.FadeIn(closing, shift=0.2 * m.UP),+ sweep.animate.set_value(2.6 * np.pi),+ run_time=2.0,+ rate_func=m.linear,+ )+ self.wait(1.0)+++if __name__ == "__main__":+ PhasedArray().render("phased_array.mp4")diff --git a/examples/wave_packet.py b/examples/wave_packet.pynew file mode 100644index 00000000..f7629438--- /dev/null+++ b/examples/wave_packet.py@@ -0,0 +1,249 @@+"""A quantum particle tunnels through a wall.++A free particle is a wave packet ψ(x, t). Drawn in 3D as the curve (x, Re ψ, Im ψ) it is a+corkscrew: its radius is |ψ| and its twist is the phase, whose crests move at half the packet's+speed. The packet meets a barrier higher than its energy, a wall a classical particle could never+cross, and splits: part reflects and part tunnels through. The Schrödinger equation+iψₜ = −½ψₓₓ + Vψ is solved as it plays, by split-step Fourier. The transmitted probability,+integrated from ψ, matches the square barrier's T = [1 + V₀² sinh²(κa) / 4E(V₀ − E)]⁻¹, averaged+over the packet's momenta.+"""++import numpy as np++import manimgx as m++N, LENGTH = 4096, 320.0 # the grid (periodic; far wider than the view)+DX = LENGTH / N+K0, SIGMA, X0 = 1.5, 5.0, -24.0 # the packet: momentum, width, start (ħ = m = 1)+V0 = 1.8 # the barrier's height, above the packet's energy K0²/2 = 1.125+WIDTH = 10 * DX # the barrier's width, ten grid cells (0.78)+DT = 0.02+SHOWN = 36.0 # the view: |x| ≤ SHOWN+X_SCALE = 0.17 # screen units per unit of x+AMP = 3.4 # screen units per unit of |ψ|+++class Packet:+ def __init__(self) -> None:+ self.x = (np.arange(N) - N // 2) * DX+ self.k = 2 * np.pi * np.fft.fftfreq(N, DX)+ self.potential = np.where(+ (self.x > -DX / 2) & (self.x < WIDTH - DX / 2), V0, 0.0+ )+ psi = np.exp(-((self.x - X0) ** 2) / (4 * SIGMA**2) + 1j * K0 * self.x)+ self.psi = psi / np.sqrt((np.abs(psi) ** 2).sum() * DX)+ self.t = 0.0++ def advance(self, until: float) -> None:+ """Split-step Fourier: half a step of the potential, a full step of the kinetic energy+ (exact in Fourier space), half a step of the potential."""+ while self.t < until - 1e-9:+ dt = min(DT, until - self.t)+ half = np.exp(-0.5j * self.potential * dt)+ kinetic = np.exp(-0.5j * self.k**2 * dt)+ self.psi = half * np.fft.ifft(kinetic * np.fft.fft(half * self.psi))+ self.t += dt++ def probability(self, where: np.ndarray) -> float:+ return float((np.abs(self.psi[where]) ** 2).sum() * DX)+++def transmission_theory() -> float:+ """The square barrier's transmission T(k), averaged over the packet's momentum distribution+ |φ(k)|² ∝ exp(−2σ²(k − k₀)²) (complex κ covers the few momenta above the barrier).+ """+ k = np.linspace(K0 - 2.5 / SIGMA, K0 + 2.5 / SIGMA, 2000)+ weight = np.exp(-2 * SIGMA**2 * (k - K0) ** 2)+ energy = k**2 / 2+ kappa = np.sqrt(2 * (V0 - energy) + 0j)+ t = 1 / (1 + V0**2 * np.sinh(kappa * WIDTH) ** 2 / (4 * energy * (V0 - energy)))+ return float((weight * t.real).sum() / weight.sum())+++def tube(+ points: np.ndarray, radius: float, sides: int = 8+) -> tuple[np.ndarray, np.ndarray]:+ """Vertices and triangles of a lit tube along a 3D polyline (parallel-transport frames)."""+ tangent = np.gradient(points, axis=0)+ tangent /= np.linalg.norm(tangent, axis=1, keepdims=True)+ seed = np.cross(tangent[0], [0.3, 0.5, 0.8])+ normals = [seed / np.linalg.norm(seed)]+ for t in tangent[1:]:+ n = normals[-1] - np.dot(normals[-1], t) * t+ normals.append(n / np.linalg.norm(n))+ n_ = np.array(normals)+ b_ = np.cross(tangent, n_)+ a = np.linspace(0, m.TAU, sides, endpoint=False)+ ring = (+ np.cos(a)[None, :, None] * n_[:, None] + np.sin(a)[None, :, None] * b_[:, None]+ )+ verts = (points[:, None] + radius * ring).reshape(-1, 3)+ i = np.arange(len(points) - 1)[:, None]+ j = np.arange(sides)[None, :]+ k = (j + 1) % sides+ tris = np.stack(+ [+ np.stack([i * sides + j, (i + 1) * sides + j, (i + 1) * sides + k], -1),+ np.stack([i * sides + j, (i + 1) * sides + k, i * sides + k], -1),+ ],+ 2,+ ).reshape(-1, 3)+ return verts, tris+++def phase_colors(psi: np.ndarray, sides: int) -> np.ndarray:+ """Per-vertex colors: hue from the phase, fading to grey where |ψ| is negligible."""+ hue = np.angle(psi) / m.TAU+ k = np.arange(3)[None, :]+ rgb = 0.55 + 0.45 * np.cos(m.TAU * (hue[:, None] - k / 3))+ strength = np.clip(np.abs(psi) / 0.04, 0, 1)[:, None]+ rows = np.ones((len(psi), 4))+ rows[:, :3] = 0.35 * (1 - strength) + rgb * strength+ return np.repeat(rows, sides, axis=0)+++class WavePacket(m.ThreeDScene):+ def construct(self) -> None:+ packet = Packet()+ clock = m.ValueTracker(0.0) # the model time shown+ view = np.flatnonzero(np.abs(packet.x) <= SHOWN)[::2]++ def curve() -> np.ndarray:+ psi = packet.psi[view]+ return np.column_stack(+ [X_SCALE * packet.x[view], AMP * psi.real, AMP * psi.imag]+ )++ verts, tris = tube(curve(), 0.03)+ spiral = m.MeshMobject(verts, tris, shade_in_3d=True)+ spiral.paint = spiral.paint.but(fill=phase_colors(packet.psi[view], 8))++ def evolve(mob: m.Mobject) -> None:+ assert isinstance(mob, m.MeshMobject)+ packet.advance(clock.get_value())+ mob.points = tube(curve(), 0.03)[0]+ mob.paint = mob.paint.but(fill=phase_colors(packet.psi[view], 8))++ spiral.add_updater(evolve)+ axis = m.Line(+ [-X_SCALE * SHOWN, 0, 0],+ [X_SCALE * SHOWN, 0, 0],+ color=m.GREY_D,+ stroke_width=1.5,+ )+ wall = m.Prism(dimensions=[X_SCALE * WIDTH, 3.0, 3.0], fill_opacity=0.28)+ wall.set_fill(m.RED_C, opacity=0.28).set_stroke(width=0)+ wall.move_to([X_SCALE * WIDTH / 2, 0, 0])++ # HUD: the textbook picture: the barrier V(x), the energy E and |ψ|² sitting on it+ plot = m.Axes(+ x_range=(-SHOWN, SHOWN, 12),+ y_range=(0, 3.2, 0.8),+ x_length=10.5,+ y_length=1.7,+ tips=False,+ axis_config={"stroke_width": 1.5, "include_ticks": False},+ ).to_edge(m.DOWN, buff=0.35)+ barrier = m.Polygon(+ plot.c2p(0, 0),+ plot.c2p(0, V0),+ plot.c2p(WIDTH, V0),+ plot.c2p(WIDTH, 0),+ stroke_width=0,+ fill_color=m.RED_C,+ fill_opacity=0.85,+ )+ energy = float(K0**2 / 2 + 1 / (8 * SIGMA**2)) # ⟨E⟩ of the Gaussian packet+ level = m.DashedLine(+ plot.c2p(-SHOWN, energy), plot.c2p(SHOWN, energy), stroke_width=1.5+ ).set_color(m.GREY_B)+ labels = m.VGroup(+ m.MathTex("V_0", font_size=26).next_to(plot.c2p(WIDTH, V0), m.RIGHT, 0.1),+ m.MathTex("E", font_size=26).next_to(plot.c2p(-SHOWN, energy), m.LEFT, 0.1),+ )+ xs = packet.x[view]++ def density() -> m.VMobject:+ top = energy + 7.0 * np.abs(packet.psi[view]) ** 2+ outline = [plot.c2p(float(a), float(b)) for a, b in zip(xs, top)]+ base = [plot.c2p(float(xs[-1]), energy), plot.c2p(float(xs[0]), energy)]+ return m.Polygon(+ *outline, *base, stroke_width=1.5, stroke_color=m.BLUE_B+ ).set_fill(m.BLUE_D, opacity=0.6)++ cloud = m.always_redraw(density)++ # HUD: the probabilities, integrated from ψ, and the theory+ left, right = packet.x < 0, packet.x >= WIDTH+ reflected = m.DecimalNumber(1, num_decimal_places=3, font_size=30)+ reflected.add_updater(lambda d: d.set_value(packet.probability(left)))+ transmitted = m.DecimalNumber(0, num_decimal_places=3, font_size=30)+ transmitted.add_updater(lambda d: d.set_value(packet.probability(right)))+ table = m.VGroup(+ m.VGroup(m.Text("reflected", font_size=26), reflected).arrange(+ m.RIGHT, buff=0.2+ ),+ m.VGroup(m.Text("tunnelled", font_size=26), transmitted).arrange(+ m.RIGHT, buff=0.2+ ),+ ).arrange(m.DOWN, aligned_edge=m.RIGHT, buff=0.18)+ table.to_corner(m.UR)+ theory = m.MathTex(+ rf"T = \left[1 + \frac{{V_0^2 \sinh^2 \kappa a}}{{4E(V_0 -"+ rf" E)}}\right]^{{-1}}"+ rf" = {transmission_theory():.3f}",+ font_size=30,+ )++ title = m.Text("A particle tunnels through a wall", font_size=38).to_corner(+ m.UL+ )+ subtitle = m.MathTex(+ r"\psi(x) \text{ drawn as }"+ r" (x,\ \operatorname{Re}\psi,\ \operatorname{Im}\psi)"+ r":\quad i\psi_t = -\tfrac12 \psi_{xx} + V\psi",+ font_size=28,+ ).set_color(m.GREY_B)+ subtitle.next_to(title, m.DOWN, aligned_edge=m.LEFT, buff=0.15)+ theory.next_to(subtitle, m.DOWN, aligned_edge=m.LEFT, buff=0.35)+ self.add_fixed_in_frame_mobjects(+ title, subtitle, plot, barrier, level, labels, cloud, table, theory+ )+ self.remove(theory)++ self.set_camera_orientation(+ phi=68 * m.DEGREES,+ theta=-52 * m.DEGREES,+ zoom=0.92,+ frame_center=np.array([0.0, 0.0, -0.75]),+ )+ self.add(axis, wall, spiral)+ # the free packet: the corkscrew turns as it goes; its crests lag behind the packet+ self.play(+ clock.animate.set_value(10.0),+ self.camera.theta_tracker.animate.set_value(-62 * m.DEGREES),+ run_time=6,+ rate_func=m.linear,+ )+ # it meets the wall: part of it comes back, part of it comes through+ self.play(+ clock.animate.set_value(24.0),+ self.camera.theta_tracker.animate.set_value(-94 * m.DEGREES),+ self.camera.phi_tracker.animate.set_value(72 * m.DEGREES),+ run_time=13,+ rate_func=m.linear,+ )+ self.play(+ clock.animate.set_value(30.0),+ m.FadeIn(theory),+ self.camera.theta_tracker.animate.set_value(-124 * m.DEGREES),+ self.camera.phi_tracker.animate.set_value(66 * m.DEGREES),+ run_time=6,+ rate_func=m.linear,+ )+ self.play(clock.animate.set_value(32.5), run_time=5, rate_func=m.linear)+++if __name__ == "__main__":+ WavePacket().render("wave_packet.mp4")