Coverage for src/manimgx/mobjects/vector_field.py: 99%
216 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« 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
6"""Ported from Manim CE 0.21 (MIT)."""
8from __future__ import annotations
10from warnings import deprecated
12__all__ = ["ArrowVectorField", "StreamLines", "VectorField"]
13import itertools as it
14import random
15from collections.abc import Callable, Sequence
16from math import ceil, floor, isfinite
17from typing import TYPE_CHECKING, Self, Unpack
19import numpy as np
21from manimgx.animation.easing import ease_out_sine, linear
22from manimgx.animation.motion import (
23 Create,
24 ShowPassingFlash,
25 UpdateFromAlphaFunc,
26 trimmed,
27)
28from manimgx.animation.timeline import (
29 Animation,
30 AnimationGroup,
31 AnimationOptions,
32 Succession,
33 Untimed,
34)
35from manimgx.constants import OUT, RIGHT, UP
36from manimgx.drawing.geometry import interpolate, inverse_interpolate, sigmoid
37from manimgx.drawing.paint import (
38 BLUE_E,
39 GREEN,
40 RED,
41 YELLOW,
42 Look,
43 ManimColor,
44 ParsableManimColor,
45 StyleBase,
46 color_to_rgb,
47 rgb_to_color,
48)
49from manimgx.mobject import Mobject, VGroup, VMobject, flow
50from manimgx.mobjects.plotting import Axes
51from manimgx.mobjects.shapes import ArrowTips, Vector
52from manimgx.settings import config
54if TYPE_CHECKING:
55 from manimgx.typing import FloatRGB, FloatRGB_Array, Point3D, Vector3D
57DEFAULT_SCALAR_FIELD_COLORS: list[ParsableManimColor] = [BLUE_E, GREEN, YELLOW, RED]
58"""The colors a vector field takes by default, from its shortest vectors to its longest:
59`BLUE_E`, `GREEN`, `YELLOW`, `RED`."""
60type FieldFunction = Callable[[Point3D], Vector3D]
61"""A vector field: a function from a point, an array of its three coordinates in scene
62coordinates, to the field's vector there."""
65def _field_ranges(
66 x_range: Sequence[float] | None,
67 y_range: Sequence[float] | None,
68 z_range: Sequence[float] | None,
69 three_dimensions: bool,
70) -> tuple[list[float], list[float], list[float]]:
71 """Where a field is sampled, per axis: (start, stop past the end, step) — the frame by default,
72 one layer in z unless three-dimensional."""
73 xs: list[float] = (
74 list(x_range)
75 if x_range
76 else [floor(-config.frame_width / 2), ceil(config.frame_width / 2)]
77 )
78 ys: list[float] = (
79 list(y_range)
80 if y_range
81 else [floor(-config.frame_height / 2), ceil(config.frame_height / 2)]
82 )
83 zs: list[float] = (
84 (list(z_range) if z_range else ys.copy())
85 if three_dimensions or z_range
86 else [0.0, 0.0]
87 )
88 for axis in (xs, ys, zs):
89 if len(axis) == 2:
90 axis.append(0.5)
91 axis[1] += axis[2]
92 return xs, ys, zs
95class VectorField(VGroup):
96 """What the vector fields have in common: a function giving a vector at every point,
97 colors by the vectors' lengths, and the tools to carry mobjects along the field.
99 A field is drawn by its kinds: as arrows
100 ([ArrowVectorField][manimgx.ArrowVectorField]) or as the lines that follow it
101 ([StreamLines][manimgx.StreamLines]). Unless given one color, each part takes the
102 field's color where it is: the vector's length there (or `color_scheme`'s value),
103 between `min_color_scheme_value` and `max_color_scheme_value`, placed along
104 `colors` and blended between them; values beyond take the first or the last color.
105 [nudge][manimgx.VectorField.nudge] carries a mobject along the field, and
106 [get_nudge_updater][manimgx.VectorField.get_nudge_updater] keeps it flowing.
108 Args:
109 func: The field: a function from a point (an array of its three coordinates, in
110 scene coordinates) to the vector there.
111 color: One color for the whole field; None to color it by its vectors.
112 color_scheme: The value a vector is colored by, a function from the vector to a
113 number; None for its length.
114 min_color_scheme_value: The value that takes the first color.
115 max_color_scheme_value: The value that takes the last color.
116 colors: The colors, spread evenly from the first value to the last.
117 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the field's group
118 itself: as it has no points, they do not restyle its parts.
119 """
121 def __init__(
122 self,
123 func: FieldFunction,
124 color: ParsableManimColor | None = None,
125 color_scheme: Callable[[Vector3D], float] | None = None,
126 min_color_scheme_value: float = 0,
127 max_color_scheme_value: float = 2,
128 colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS,
129 **kwargs: Unpack[StyleBase],
130 ):
131 super().__init__(**kwargs)
132 self.func = func
133 """The field: its function, from a point to the vector there."""
134 if color is None:
135 self.single_color = False
136 self.color_scheme: Callable[[Vector3D], float] = color_scheme or (
137 lambda vec: float(np.linalg.norm(vec))
138 )
139 self.rgbs: FloatRGB_Array = np.array(list(map(color_to_rgb, colors)))
141 self._color_range = (min_color_scheme_value, max_color_scheme_value)
142 else:
143 self.single_color = True
144 self.color = ManimColor.parse(color)
145 self.submob_movement_updater: Callable[[VectorField, float], object] | None = (
146 None
147 )
149 @deprecated("use pos_to_color", category=None)
150 def pos_to_rgb(self, pos: Point3D) -> FloatRGB:
151 """The field's RGB color at a point, using its current function and palette."""
152 if self.single_color:
153 return self.color.to_rgb()
154 low, high = self._color_range
155 color_value = np.clip(self.color_scheme(self.func(pos)), low, high)
156 alpha = inverse_interpolate(low, high, color_value)
157 alpha *= len(self.rgbs) - 1
158 c1: FloatRGB = self.rgbs[int(alpha)]
159 c2: FloatRGB = self.rgbs[min(int(alpha + 1), len(self.rgbs) - 1)]
160 return interpolate(c1, c2, alpha % 1)
162 def pos_to_color(self, pos: Point3D) -> ManimColor:
163 """The field's color at a point."""
164 return rgb_to_color(self.pos_to_rgb(pos))
166 @staticmethod
167 def shift_func(func: FieldFunction, shift_vector: np.ndarray) -> FieldFunction:
168 """Move a field: make the function of the field shifted by a vector.
170 Args:
171 func: The field's function.
172 shift_vector: The vector to move it by, in scene units.
174 Returns:
175 A new function, which at a point p is `func(p - shift_vector)`.
176 """
177 return lambda p: func(p - shift_vector)
179 @staticmethod
180 def scale_func(func: FieldFunction, scalar: float) -> FieldFunction:
181 """Rescale a field's pattern: make the function of the field whose vector at a
182 point p is the old field's at p × `scalar`.
184 A scalar below 1 spreads the pattern out, as if zoomed in; above 1, it draws it
185 together. The vectors keep their lengths.
187 Args:
188 func: The field's function.
189 scalar: The factor the points are multiplied by.
191 Returns:
192 A new function, which at a point p is `func(p * scalar)`.
193 """
194 return lambda p: func(p * scalar)
196 def fit_to_coordinate_system(self, coordinate_system: Axes) -> Self:
197 """Place the field on axes: move each point of its parts to the axes' point
198 whose coordinates are the point's own.
200 A field made in the axes' coordinates (its ranges theirs) lands on them, its
201 arrows stretched with the axes' units.
203 Args:
204 coordinate_system: The axes.
206 Examples:
207 ```python
208 import numpy as np
210 import manimgx as m
213 class VectorFieldFitToCoordinateSystemExample(m.Scene):
214 def construct(self) -> None:
215 axes = m.Axes(
216 x_range=[-2, 2], y_range=[-2, 2], x_length=7, y_length=7
217 )
218 field = m.ArrowVectorField(
219 lambda p: np.array([-p[1], p[0], 0]) / 2,
220 x_range=[-2, 2, 0.5],
221 y_range=[-2, 2, 0.5],
222 )
223 self.add(axes, field.fit_to_coordinate_system(axes))
224 ```
225 """
226 self.apply_function(lambda pos: coordinate_system.coords_to_point(*pos))
227 return self
229 def nudge(
230 self, mob: Mobject, dt: float = 1, substeps: int = 1, pointwise: bool = False
231 ) -> Self:
232 """Carry a mobject along the field for a while, as a particle on its flow.
234 The field's vectors are velocities: the mobject moves with the field at its
235 center, or, with `pointwise`, each of its points moves with the field where it
236 is, which bends it. Each step is a fourth-order Runge–Kutta step.
238 Args:
239 mob: The mobject to move.
240 dt: How long it is carried, in the field's time; negative to carry it back.
241 substeps: How many steps the time is divided into: more follow the field
242 more closely.
243 pointwise: Whether each point of the mobject moves on its own, rather than
244 the whole mobject with its center.
245 """
247 def runge_kutta(p: Point3D, step_size: float) -> Vector3D:
248 k_1 = self.func(p)
249 k_2 = self.func(p + step_size * (k_1 * 0.5))
250 k_3 = self.func(p + step_size * (k_2 * 0.5))
251 k_4 = self.func(p + step_size * k_3)
252 return step_size / 6.0 * (k_1 + 2.0 * k_2 + 2.0 * k_3 + k_4)
254 step_size = dt / substeps
255 for _ in range(substeps):
256 if pointwise:
257 mob.apply_function(lambda p: p + runge_kutta(p, step_size))
258 else:
259 mob.shift(runge_kutta(mob.get_center(), step_size))
260 return self
262 def nudge_submobjects(
263 self, dt: float = 1, substeps: int = 1, pointwise: bool = False
264 ) -> Self:
265 """Carry each of the field's own parts along it for a while, as
266 [nudge][manimgx.VectorField.nudge] carries a mobject.
268 Args:
269 dt: How long they are carried, in the field's time; negative to carry them
270 back.
271 substeps: How many steps the time is divided into.
272 pointwise: Whether each point of a part moves on its own, rather than the
273 whole part with its center.
274 """
275 for mob in self.submobjects:
276 self.nudge(mob, dt, substeps, pointwise)
277 return self
279 def get_nudge_updater(
280 self, speed: float = 1, pointwise: bool = False
281 ) -> Callable[[Mobject, float], Mobject]:
282 """Make an updater that carries a mobject along the field: added to a mobject,
283 it moves it with the field every frame, by the time since the last.
285 Args:
286 speed: How fast the mobject is carried: the field's time per second.
287 pointwise: Whether each point of the mobject moves on its own, rather than
288 the whole mobject with its center.
290 Returns:
291 The updater, a function of the mobject and the time step, to give
292 [add_updater][manimgx.Mobject.add_updater].
294 Examples:
295 ```python
296 import numpy as np
298 import manimgx as m
301 class VectorFieldGetNudgeUpdaterExample(m.Scene):
302 def construct(self) -> None:
303 def swirl(p: np.ndarray) -> np.ndarray:
304 return np.sin(p[1] / 2) * m.RIGHT + np.cos(p[0] / 2) * m.UP
306 field = m.ArrowVectorField(
307 swirl, x_range=[-7, 7, 1], y_range=[-4, 4, 1]
308 )
309 circle = m.Circle(radius=1, color=m.YELLOW).shift(2 * m.LEFT)
310 dot = m.Dot(2 * m.RIGHT, radius=0.15, color=m.RED)
311 circle.add_updater(field.get_nudge_updater(pointwise=True))
312 dot.add_updater(field.get_nudge_updater())
313 self.add(field, circle, dot)
314 self.wait(2.5)
315 ```
316 """
317 return lambda mob, dt: self.nudge(mob, dt * speed, pointwise=pointwise)
319 def start_submobject_movement(
320 self, speed: float = 1, pointwise: bool = False
321 ) -> Self:
322 """Set the field's own parts moving along it: an updater carries them every
323 frame, as [nudge_submobjects][manimgx.VectorField.nudge_submobjects] does.
325 A movement already started is replaced.
327 Args:
328 speed: How fast they are carried: the field's time per second.
329 pointwise: Whether each point of a part moves on its own, rather than the
330 whole part with its center.
331 """
332 self.stop_submobject_movement()
333 self.submob_movement_updater = lambda mob, dt: mob.nudge_submobjects(
334 dt * speed, pointwise=pointwise
335 )
336 self.add_updater(self.submob_movement_updater)
337 return self
339 def stop_submobject_movement(self) -> Self:
340 """Stop the movement
341 [start_submobject_movement][manimgx.VectorField.start_submobject_movement]
342 started, if any.
343 """
344 if self.submob_movement_updater is not None:
345 self.remove_updater(self.submob_movement_updater)
346 self.submob_movement_updater = None
347 return self
350class ArrowVectorField(VectorField):
351 """A vector field drawn as arrows: one at each point of a grid, from the point in
352 the field's direction there; colored by the vectors' lengths, blue to red, unless
353 given a color.
355 The grid spans `x_range` and `y_range` — by default the frame, every half unit — in
356 the plane z = 0, or through `z_range` too. Each arrow is as long as `length_func`
357 makes of its vector's length: by default 0.45 × sigmoid(length), from 0.225 for the
358 shortest vectors to 0.45 for the longest, so that neighbours do not overlap (a zero
359 vector makes no arrow).
361 Args:
362 func: The field: a function from a point (an array of its three coordinates, in
363 scene coordinates) to the vector there.
364 color: One color for every arrow; None to color them by their vectors.
365 color_scheme: The value a vector is colored by, a function from the vector to a
366 number; None for its length.
367 min_color_scheme_value: The value that takes the first color.
368 max_color_scheme_value: The value that takes the last color.
369 colors: The colors, spread evenly from the first value to the last.
370 x_range: The grid's x values, `[x_min, x_max, x_step]` with both ends, or
371 `[x_min, x_max]` for a step of 0.5; None for the frame's width, [-8, 8].
372 y_range: The grid's y values, likewise; None for the frame's height, [-4, 4].
373 z_range: The grid's z values, likewise; None for z = 0 alone, or the y values
374 with `three_dimensions`.
375 three_dimensions: Whether the grid spans z too: by `z_range`, or by the y
376 values.
377 length_func: The arrows' length, as a function of their vectors' length.
378 opacity: The arrows' opacity, from 0 to 1.
379 vector_config: [Arrow keywords][manimgx.Arrow] for the
380 arrows: their tips, `stroke_width`, …; None for none.
381 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the field's group
382 itself: as it has no points, they do not restyle its arrows.
384 Examples:
385 ```python
386 import numpy as np
388 import manimgx as m
391 class ArrowVectorFieldExample(m.Scene):
392 def construct(self) -> None:
393 field = m.ArrowVectorField(lambda p: np.array([-p[1], p[0], 0]) / 2)
394 self.add(field)
395 ```
396 """
398 def __init__(
399 self,
400 func: FieldFunction,
401 color: ParsableManimColor | None = None,
402 color_scheme: Callable[[Vector3D], float] | None = None,
403 min_color_scheme_value: float = 0,
404 max_color_scheme_value: float = 2,
405 colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS,
406 x_range: Sequence[float] | None = None,
407 y_range: Sequence[float] | None = None,
408 z_range: Sequence[float] | None = None,
409 three_dimensions: bool = False,
410 length_func: Callable[[float], float] = lambda norm: 0.45 * sigmoid(norm),
411 opacity: float = 1.0,
412 vector_config: ArrowTips | None = None,
413 **kwargs: Unpack[StyleBase],
414 ):
415 x_range, y_range, z_range = _field_ranges(
416 x_range, y_range, z_range, three_dimensions
417 )
418 super().__init__(
419 func,
420 color,
421 color_scheme,
422 min_color_scheme_value,
423 max_color_scheme_value,
424 colors,
425 **kwargs,
426 )
427 self.length_func = length_func
428 self.vector_config: ArrowTips = vector_config or {}
429 grid = it.product(np.arange(*x_range), np.arange(*y_range), np.arange(*z_range))
430 self.add(*(self.get_vector(x * RIGHT + y * UP + z * OUT) for x, y, z in grid))
431 self.set_opacity(opacity)
433 def get_vector(self, point: Point3D) -> Vector:
434 """Make the field's arrow at a point: from the point, in the field's direction
435 there, as long as `length_func` makes it, in the field's color there.
437 Args:
438 point: The point, in scene coordinates.
440 Returns:
441 A new [Vector][manimgx.Vector], not added to the field.
442 """
443 output = np.array(self.func(point), dtype=float)
444 norm = np.linalg.norm(output)
445 if norm != 0:
446 output *= self.length_func(float(norm)) / norm
447 vect = Vector(output, **self.vector_config)
448 vect.shift(point)
449 vect.set_color(self.color if self.single_color else self.pos_to_color(point))
450 return vect
453class StreamLine(VMobject):
454 """One stream line and its current phase, in the field's time."""
456 anim: Animation
457 time: float
460class StreamLines(VectorField):
461 """A vector field drawn as the lines that follow it: from points spread over a grid,
462 the paths of particles the field carries; colored by the vectors' lengths, blue to
463 red, unless given a color.
465 The lines start at the points of a grid (`x_range`, `y_range`, `z_range`, as an
466 [ArrowVectorField][manimgx.ArrowVectorField]'s), each moved a little at random —
467 the same way every time — and `n_repeats` near each point. Each follows the field
468 in steps of `dt` for `virtual_time`, and stops where it leaves the grid's box,
469 widened by `padding`. A line takes the field's colors at its points, in a gradient
470 from its start to its end. [create][manimgx.StreamLines.create] draws them in;
471 [start_animation][manimgx.StreamLines.start_animation] sets them flowing, and
472 [end_animation][manimgx.StreamLines.end_animation] ends the flow.
474 Args:
475 func: The field: a function from a point (an array of its three coordinates, in
476 scene coordinates) to the vector there.
477 color: One color for every line; None to color them by their vectors.
478 color_scheme: The value a vector is colored by, a function from the vector to a
479 number; None for its length.
480 min_color_scheme_value: The value that takes the first color.
481 max_color_scheme_value: The value that takes the last color.
482 colors: The colors, spread evenly from the first value to the last.
483 x_range: The x values of the lines' starts, `[x_min, x_max, x_step]` with both
484 ends, or `[x_min, x_max]` for a step of 0.5; None for the frame's width,
485 [-8, 8].
486 y_range: The y values of the starts, likewise; None for the frame's height,
487 [-4, 4].
488 z_range: The z values of the starts, likewise; None for z = 0 alone, or the y
489 values with `three_dimensions`.
490 three_dimensions: Whether the starts span z too: by `z_range`, or by the y
491 values.
492 noise_factor: How far each start may be moved, in scene units: up to half of it
493 either way, in each coordinate; None for half the y step.
494 n_repeats: How many lines start near each point of the grid.
495 dt: The time step the lines are traced with: smaller follows the field more
496 closely.
497 virtual_time: How long each line follows the field, in the field's time: longer
498 makes longer lines.
499 max_anchors_per_line: The most points a line is smoothed through.
500 padding: How far beyond the grid the lines may go before they stop, in scene
501 units.
502 stroke_width: The lines' width, in hundredths of a scene unit.
503 opacity: The lines' opacity, from 0 to 1.
505 Examples:
506 ```python
507 import numpy as np
509 import manimgx as m
512 class StreamLinesExample(m.Scene):
513 def construct(self) -> None:
514 def func(p: np.ndarray) -> np.ndarray:
515 return np.sin(p[0] / 2) * m.UR + np.cos(p[1] / 2) * m.LEFT
517 self.add(m.StreamLines(func, stroke_width=2, padding=1))
518 ```
519 """
521 def __init__(
522 self,
523 func: FieldFunction,
524 color: ParsableManimColor | None = None,
525 color_scheme: Callable[[Vector3D], float] | None = None,
526 min_color_scheme_value: float = 0,
527 max_color_scheme_value: float = 2,
528 colors: Sequence[ParsableManimColor] = DEFAULT_SCALAR_FIELD_COLORS,
529 x_range: Sequence[float] | None = None,
530 y_range: Sequence[float] | None = None,
531 z_range: Sequence[float] | None = None,
532 three_dimensions: bool = False,
533 noise_factor: float | None = None,
534 n_repeats: int = 1,
535 dt: float = 0.05,
536 virtual_time: float = 3,
537 max_anchors_per_line: int = 100,
538 padding: float = 3,
539 stroke_width: float = 1,
540 opacity: float = 1,
541 **kwargs: Unpack[Look],
542 ):
543 x_range, y_range, z_range = _field_ranges(
544 x_range, y_range, z_range, three_dimensions
545 )
546 super().__init__(
547 func,
548 color,
549 color_scheme,
550 min_color_scheme_value,
551 max_color_scheme_value,
552 colors,
553 **kwargs,
554 )
555 noise_factor = noise_factor if noise_factor is not None else y_range[2] / 2
556 self.virtual_time = virtual_time
557 """How long each line follows the field, in the field's time."""
558 self.stroke_width = stroke_width
559 half_noise = noise_factor / 2
560 rng = np.random.default_rng(0)
561 start_points = np.array(
562 [
563 (x - half_noise) * RIGHT
564 + (y - half_noise) * UP
565 + (z - half_noise) * OUT
566 + noise_factor * rng.random(3)
567 for n in range(n_repeats)
568 for x in np.arange(*x_range)
569 for y in np.arange(*y_range)
570 for z in np.arange(*z_range)
571 ]
572 )
573 pad = padding
574 (x0, x1, xs), (y0, y1, ys), (z0, z1, zs) = (
575 x_range,
576 y_range,
577 z_range,
578 )
580 def outside_box(p: Point3D) -> bool:
581 return bool(
582 p[0] < x0 - pad
583 or p[0] > x1 + pad - xs
584 or p[1] < y0 - pad
585 or p[1] > y1 + pad - ys
586 or p[2] < z0 - pad
587 or p[2] > z1 + pad - zs
588 )
590 max_steps = ceil(virtual_time / dt) + 1
591 self.stream_lines: list[StreamLine] = []
592 """The lines, in the order of their starts."""
593 for point in start_points:
594 points = [point]
595 for _ in range(max_steps):
596 new_point = points[-1] + dt * func(points[-1])
597 if outside_box(new_point):
598 break
599 points.append(new_point)
600 line = StreamLine()
601 line.set_points_smoothly(
602 points[:: max(1, int(len(points) / max_anchors_per_line))]
603 )
604 if self.single_color:
605 line.set_stroke(
606 color=self.color, width=self.stroke_width, opacity=opacity
607 )
608 else: # the field's color at each anchor, in order along the line: the gradient
609 # runs from the line's start to its end (not across its box)
610 line.set_stroke([self.pos_to_color(p) for p in line.get_anchors()])
611 line.set_stroke(width=self.stroke_width, opacity=opacity)
612 travel = np.sign(line.get_end() - line.get_start())
613 if travel.any():
614 line.set_sheen_direction(travel)
615 self.add(line)
616 self.stream_lines.append(line)
617 self.flow_animation: Callable[[StreamLines, float], None] | None = None
619 def create(self, **kwargs: Unpack[AnimationOptions]) -> AnimationGroup:
620 """Make an animation that draws the lines in, one after another in a random
621 order.
623 Each line is drawn with [Create][manimgx.Create] over `run_time`, by default
624 the field's `virtual_time`, each beginning `lag_ratio` of that after the one
625 before: by default `run_time / 2` divided by the number of lines. The order is
626 shuffled with Python's `random` (seed it for the same order every time).
628 Args:
629 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]
630 for each line's animation, and `lag_ratio` for the whole.
632 Returns:
633 A new animation group.
635 Examples:
636 ```python
637 import manimgx as m
640 class StreamLinesCreateExample(m.Scene):
641 def construct(self) -> None:
642 stream_lines = m.StreamLines(
643 lambda p: (p[0] * m.UR + p[1] * m.LEFT) - p,
644 color=m.YELLOW,
645 x_range=[-7, 7, 1],
646 y_range=[-4, 4, 1],
647 stroke_width=3,
648 virtual_time=1,
649 max_anchors_per_line=6,
650 )
651 self.play(stream_lines.create())
652 ```
653 """
654 run_time = kwargs.pop("run_time", self.virtual_time)
655 lag_ratio = kwargs.pop("lag_ratio", run_time / 2 / len(self.submobjects))
656 kwargs["run_time"] = run_time
657 animations = [Create(line, **kwargs) for line in self.stream_lines]
658 random.shuffle(animations)
659 return AnimationGroup(*animations, lag_ratio=lag_ratio)
661 def start_animation(
662 self,
663 warm_up: bool = True,
664 flow_speed: float = 1,
665 time_width: float = 0.3,
666 line_animation_class: type[ShowPassingFlash] = ShowPassingFlash,
667 **kwargs: Unpack[Untimed],
668 ) -> Self:
669 """Set the lines flowing: each flashes along itself, over and over, while the
670 scene plays or waits.
672 An updater plays each line's animation — by default a
673 [ShowPassingFlash][manimgx.ShowPassingFlash] — along the line again and again,
674 a cycle every `virtual_time / flow_speed` seconds, each line at a phase of its
675 own, drawn with Python's `random`.
676 [end_animation][manimgx.StreamLines.end_animation] ends the flow.
677 Starting again replaces the previous flow.
679 Args:
680 warm_up: Whether each line waits, empty, until its own time to begin,
681 rather than all flowing from the start.
682 flow_speed: How fast the lines flow: the field's time per second, positive
683 and finite.
684 time_width: The length of each flash, as a fraction of its line.
685 line_animation_class: The animation played along each line: a
686 ShowPassingFlash, or a class of its kind.
687 **kwargs: [Animation options][manimgx.animation.timeline.Untimed] for each
688 line's animation, but `run_time`; `rate_func` is `linear` unless given.
690 Examples:
691 ```python
692 import numpy as np
694 import manimgx as m
697 class StreamLinesStartAnimationExample(m.Scene):
698 def construct(self) -> None:
699 def func(p: np.ndarray) -> np.ndarray:
700 return np.sin(p[0] / 2) * m.UR + np.cos(p[1] / 2) * m.LEFT
702 stream_lines = m.StreamLines(
703 func, stroke_width=3, max_anchors_per_line=7
704 )
705 self.add(stream_lines)
706 stream_lines.start_animation(warm_up=False, flow_speed=1.5)
707 self.wait(stream_lines.virtual_time / stream_lines.flow_speed)
708 ```
709 """
710 if not isfinite(flow_speed) or flow_speed <= 0:
711 raise ValueError("flow_speed must be positive and finite")
712 run_time = self.virtual_time / flow_speed
713 if not isfinite(run_time) or run_time <= 0:
714 raise ValueError("the flow's cycle duration must be positive and finite")
715 if self.flow_animation is not None:
716 self.remove_updater(self.flow_animation)
717 for line in self.stream_lines:
718 line.anim.finish()
719 kwargs.setdefault("rate_func", linear)
720 for line in self.stream_lines:
721 line.anim = line_animation_class(
722 line,
723 run_time=run_time,
724 time_width=time_width,
725 **kwargs,
726 )
727 line.anim.begin()
728 line.time = random.random() * self.virtual_time * (-1 if warm_up else 1)
729 self.add(line.anim.mobject)
731 def updater(mob: StreamLines, dt: float) -> None:
732 for line in mob.stream_lines:
733 line.time += dt * flow_speed
734 if line.time >= mob.virtual_time:
735 line.time %= mob.virtual_time
736 line.anim.interpolate(max(line.time, 0) / mob.virtual_time)
738 self.add_updater(flow(updater), call_updater=True)
739 self.flow_animation = updater
740 self.flow_speed = flow_speed
741 self.time_width = time_width
742 return self
744 def end_animation(self) -> AnimationGroup:
745 """Make an animation that ends the flow: each line finishes its flash, then is
746 drawn in with [Create][manimgx.Create], easing out.
748 The flow's updater is removed at once, and a line still waiting to begin stays
749 hidden until its time. Called before
750 [start_animation][manimgx.StreamLines.start_animation], it raises a
751 ValueError. The lines stay in the field, whole and in their original paint.
753 Returns:
754 A new animation group.
755 """
756 if self.flow_animation is None:
757 raise ValueError("You have to start the animation before fading it out.")
759 def hide_and_wait(mob: Mobject, alpha: float) -> None: # unseen until its turn
760 trimmed(mob, 0, float(alpha >= 1))
762 def finish_cycle(start: float) -> Callable[[StreamLine, float], None]:
763 """The flow, on to the end of the line's cycle: its time at alpha (linear)."""
765 def flow(line: StreamLine, alpha: float) -> None:
766 line.time = start + alpha * (self.virtual_time - start)
767 line.anim.interpolate(line.time / self.virtual_time)
768 if alpha == 1:
769 line.anim.finish()
770 trimmed(line, 0, 1)
772 return flow
774 max_run_time = self.virtual_time / self.flow_speed
775 creation_rate_func = ease_out_sine
776 creation_staring_speed = creation_rate_func(0.001) * 1000
777 creation_run_time = (
778 max_run_time / (1 + self.time_width) * creation_staring_speed
779 )
780 animations: list[Animation] = []
781 self.remove_updater(self.flow_animation)
782 self.flow_animation = None
783 for line in self.stream_lines:
784 create = Create(
785 line, run_time=creation_run_time, rate_func=creation_rate_func
786 )
787 if line.time <= 0:
788 animations.append(
789 Succession(
790 UpdateFromAlphaFunc(
791 line, hide_and_wait, run_time=-line.time / self.flow_speed
792 ),
793 create,
794 )
795 )
796 line.anim.finish()
797 else:
798 remaining_time = max_run_time - line.time / self.flow_speed
799 animations.append(
800 Succession(
801 UpdateFromAlphaFunc(
802 line,
803 finish_cycle(line.time),
804 run_time=remaining_time,
805 rate_func=linear,
806 ),
807 create,
808 )
809 )
810 return AnimationGroup(*animations)