Skip to content

Reference Documentation

Documentation for all classes and functions within manim-fourier-series.

Documentation for FourierSeries

A class representing a Fourier series animation for Manim.

This uses points generated from text, images, svgs, polygons, or manually to solve for circles and arrows that approximate the input.

Source code in manim_fourier_series/main.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
class FourierSeries:
    """A class representing a Fourier series animation for Manim.

    This uses points generated from text, images, svgs, polygons, or
    manually to solve for circles and arrows that approximate the input.
    """

    def __init__(
        self,
        points: np.ndarray,
        number: int = 50,
        fade: float = 0.005,
        circle_opacity: float = 0.5,
        arrow_opacity: float = 0.8,
        width: Optional[int] = None,
        height: Optional[int] = None,
        shift: Optional[complex] = 0,
    ):
        """Initialize the FourierSeries object.

        Parameters
        ----------
        points : np.ndarray
            The points to generate the Fourier series from. This can be generated
            from the `text`, `image`, or `polygon` static methods on this class.
        number : int, optional
            How many circles should be generated. The more circles, the more precise the output, but the longer time to render. By default 50
        fade : float, optional
            The rate at which the path should fade. The path exponentially fades by this amount each frame. By default 0.005
        circle_opacity : float, optional
            The opacity of the circles, by default 0.5
        arrow_opacity : float, optional
            The opacity of the arrows, by default 0.8
        width : int, optional
            The width of the window. If None, then this will occupy the entire window. The points will only be scaled uniformly. By default None
        height : int, optional
            The height of the window. If None, then this will occupy the entire window. The points will only be scaled uniformly. By default None
        shift : Optional[complex], optional
            The amount to shift the points by. By default 0

        Examples
        --------
        The following code animates a Fourier series for a nonagon.

        ```py
        points = FourierSeries.polygon(9)
        fs = FourierSeries(points)
        self.add(fs.mobject)

        self.play(fs.revolve(1), run_time=5, rate_func=linear)
        ```
        """
        points = normalize(points, width=width, height=height) + shift

        self.points = points
        self.N = min(number, len(self.points))
        self.fade = fade

        self.amplitudes, self.frequencies, self.phases = fft(self.points, self.N)

        self.tracker = ValueTracker(0)

        self.arrows = [
            Arrow(
                ORIGIN,
                RIGHT,
                stroke_opacity=arrow_opacity,
                tip_style={
                    "stroke_opacity": arrow_opacity,
                    "fill_opacity": arrow_opacity,
                },
            )
            for _ in range(self.N)
        ]
        self.circles = [
            Circle(
                radius=self.amplitudes[i],
                color=TEAL,
                stroke_width=2,
                stroke_opacity=circle_opacity,
            )
            for i in range(self.N)
        ]

        self.path = NestedPath()

        self.values = ArrayMobject()
        self.cumulative = ArrayMobject()

        self.values.add_updater(
            lambda array, dt: array.set_data(
                np.array(
                    [0]
                    + [
                        a * np.exp(1j * (p + self.tracker.get_value() * f))
                        for a, f, p in zip(
                            self.amplitudes, self.frequencies, self.phases
                        )
                    ]
                )
            ),  # This lambda sets the value to e^i(a + wt)
            call_updater=True,
        )
        self.cumulative.add_updater(
            lambda array, dt: array.become(self.values.sum()), call_updater=True
        )

        for i, (arrow, ring) in enumerate(zip(self.arrows, self.circles)):
            arrow.idx = i
            ring.idx = i
            ring.add_updater(
                lambda ring: ring.move_to(complex_to_R3(self.cumulative[ring.idx]))
            )
            arrow.add_updater(
                lambda arrow: arrow.become(
                    Arrow(
                        complex_to_R3(self.cumulative[arrow.idx]),
                        complex_to_R3(self.cumulative[arrow.idx + 1]),
                        buff=0,
                        max_tip_length_to_length_ratio=0.2,
                        stroke_width=2,
                        stroke_opacity=arrow_opacity,
                        tip_style={
                            "stroke_opacity": arrow_opacity,
                            "fill_opacity": arrow_opacity,
                        },
                    )
                )
            )

        self.path.set_points_as_corners([complex_to_R3(self.cumulative[-1])] * 2)
        self.path.add_updater(
            lambda path: path.updater(complex_to_R3(self.cumulative[-1]), self.fade)
        )

        self.mobject = Group(
            *self.arrows, *self.circles, self.values, self.cumulative, self.path
        )

    def zoomed_display(
        self, scene: ZoomedScene, animate: bool = True, scale_factor: float = 2
    ) -> FourierSeries:
        """Add a window to the scene that follows the path.

        Parameters
        ----------
        scene : ZoomedScene
            The scene to add the window to. This must be a `ZoomedScene` otherwise the window will not work.
        animate : bool, optional
            Whether or not the window's entrance should be animated, by default True
        scale_factor : float, optional
            How much the zoomed camera should be scaled by. The smaller, the more zoomed in. By default 2

        Returns
        -------
        FourierSeries
            Self, for chaining purposes

        Raises
        ------
        AssertionError
            If the scene is not a `ZoomedScene`

        Examples
        --------
        The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

        ```py
        class BasicExample(ZoomedScene):
            def construct(self):
                points = FourierSeries.text("Guru", r"path/to/font.ttf")

                fs = FourierSeries(points)
                self.add(fs.mobject)

                fs.zoomed_display(self)

                self.play(fs.revolve(1), run_time=5, rate_func=linear)
        ```
        """
        assert isinstance(scene, ZoomedScene), "The scene must be a ZoomedScene"

        scene.zoomed_camera.frame.scale(scale_factor)
        scene.zoomed_camera.frame.move_to(complex_to_R3(self.cumulative[-1]))

        scene.activate_zooming(animate)

        scene.zoomed_camera.frame.add_updater(
            lambda frame: frame.move_to(complex_to_R3(self.cumulative[-1]))
        )

        return self

    def revolve(self, revolutions: float = 1) -> Animation:
        """Animate the Fourier series.

        Parameters
        ----------
        revolutions : float, optional
            How many times the image should be drawn, by default 1

        Returns
        -------
        Animation
            An animation that can be passed to `self.play`. A linear rate function is highly recommended.

        Examples
        --------
        The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

        ```py
        points = FourierSeries.text("Guru", r"path/to/font.ttf")
        fs = FourierSeries(points)
        self.add(fs.mobject)

        self.play(fs.revolve(1), run_time=5, rate_func=linear) # A linear rate function is highly recommended
        ```
        """
        return self.tracker.animate.set_value(revolutions * 2 * np.pi)

    def display_complete_path(self, opacity: float = 0.5) -> FourierSeries:
        """Displays the entire path that the Fourier series will go through.

        Parameters
        ----------
        opacity : float, optional
            The opacity of the path, by default 0.5

        Returns
        -------
        FourierSeries
            Self, for chaining purposes
        """
        self.path.clear_updaters()
        self.path.set_points_as_corners([complex_to_R3(point) for point in self.points])
        self.path.set_stroke(opacity=opacity)
        return self

    ## Static methods for point generation

    @staticmethod
    def polygon(n: int) -> np.ndarray:
        """Generate a set of points from a regular polygon.

        Parameters
        ----------
        n : int
            The number of sides the polygon should have.

        Returns
        -------
        np.ndarray
            The points generated from the polygon. Pass this to the FourierSeries constructor.

        Examples
        --------
        The following code generates a set of points from a regular pentagon and then animates it through a Fourier series.

        ```py
        points = FourierSeries.polygon(5)
        fs = FourierSeries(points)
        self.add(fs.mobject)

        self.play(fs.revolve(1), run_time=5, rate_func=linear)
        ```
        """
        points = np.array(
            [
                np.linspace(
                    np.exp(2j * k * np.pi / n), np.exp(2j * (k + 1) * np.pi / n), 1000
                )
                for k in range(n)
            ]
        ).reshape(-1)

        points *= 1j
        if not n % 2:
            points *= np.exp(1j * np.pi / n)
        return points

    @staticmethod
    def text(
        text: str,
        font: str,
        remove_internal: bool = True,
        multiple_contours: bool = False,
    ) -> np.ndarray:
        """Generate a set of points from text.

        Parameters
        ----------
        text : str
            The text to generate points from.
        font : str
            A path to a font file, to be passed to `PIL.ImageFont.truetype`. A cursive font
            is highly recommended for multiple letters. Try [Brush Script MT](https://github.com/PeculiarProgrammer/manim-fourier-series/raw/refs/heads/master/examples/fonts/brush.ttf) or similar.
        remove_internal : bool, optional
            Whether or not internal contours should be removed. In simple terms, when this
            is True, any paths that are within another path will not be rendered. For
            instance, an `o` would not have the interior line drawn, only the exterior.
            By default True
        multiple_contours : bool, optional
            Whether or not multiple contours are allowed. If this is False, only the contour
            occupying the largest area will be displayed. Note that this cannot be False
            when `remove_internal` is False. By default False

        Returns
        -------
        np.ndarray
            The points generated from the text. Pass this to the FourierSeries constructor.
            Note that the points will be an array of complex numbers.

        Examples
        --------
        The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

        ```py
        points = FourierSeries.text("Guru", r"path/to/font.ttf")
        fs = FourierSeries(points)
        self.add(fs.mobject)
        ```
        """
        font_file = ImageFont.truetype(font, size=1000)

        mask = font_file.getmask(text, mode="1")

        image = Image.frombytes(mask.mode, mask.size, bytes(mask))
        image = np.array(image)

        return extract_edges(
            image, greedy_shortest_path, False, remove_internal, multiple_contours
        )

    @staticmethod
    def image(
        filename: str,
        greedy: bool = False,
        remove_internal: bool = True,
        multiple_contours: bool = False,
    ) -> np.ndarray:
        """Generate a set of points from the edges of an image.

        Parameters
        ----------
        filename : str
            Where the image is located.
        greedy : bool, optional
            This should normally be False, however if the image was rendered poorly, such as with
            peculiar lines, try setting this to True. By default False
        remove_internal : bool, optional
            Whether or not internal contours should be removed. In simple terms, when this
            is True, any paths that are within another path will not be rendered. For
            instance, an `o` would not have the interior line drawn, only the exterior.
            By default True
        multiple_contours : bool, optional
            Whether or not multiple contours are allowed. If this is False, only the contour
            occupying the largest area will be displayed. Note that this cannot be False
            when `remove_internal` is False. By default False

        Returns
        -------
        np.ndarray
            The points generated from the image. Pass this to the FourierSeries constructor.
            Note that the points will be an array of complex numbers.

        Examples
        --------

        The following code generates a set of points from an image of a bird and then animates it through a Fourier series.
        ```py
        points = FourierSeries.image(r"path/to/bird.jpg")
        fs = FourierSeries(points)
        self.add(fs.mobject)
        ```
        """
        image = cv2.imread(filename)

        scale = min(
            920 / image.shape[0], 1080 / image.shape[1]
        )  # Scale image to be no greater than 1080 x 920
        image = cv2.resize(
            image, (int(image.shape[1] * scale), int(image.shape[0] * scale))
        )

        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        image = 255 - cv2.adaptiveThreshold(
            image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2
        )  # Determine different areas

        contours, _ = cv2.findContours(
            image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
        )  # Find outlines of areas

        largest = max(contours, key=cv2.contourArea)  # Find the largest area

        image = np.zeros(
            image.shape, dtype=image.dtype
        )  # Shade everything that isn't the largest area

        cv2.drawContours(image, [largest], -1, (255, 255, 255), -1)

        if greedy:
            return extract_edges(
                image,
                greedy_shortest_path,
                remove_internal=remove_internal,
                multiple_contours=multiple_contours,
            )
        return extract_edges(
            image, remove_internal=remove_internal, multiple_contours=multiple_contours
        )

    @staticmethod
    def numpy_points(filename: str) -> np.ndarray:
        """Load a set of points from a numpy file.

        Parameters
        ----------
        filename : str
            Where the numpy file is located.

        Returns
        -------
        np.ndarray
            The points loaded from the numpy file. Pass this to the FourierSeries constructor.
            Note that the points will be an array of complex numbers.

        Examples
        --------
        The following code loads a set of points from a numpy file and then animates it through a Fourier series.

        ```py
        points = FourierSeries.numpy_points(r"path/to/points.npy")
        fs = FourierSeries(points)
        self.add(fs.mobject)
        ```
        """
        return np.load(filename)

    @staticmethod
    def svg(filename: str) -> np.ndarray:
        """Generate a set of points from an SVG file.

        Parameters
        ----------
        filename : str
            Where the SVG file is located.

        Returns
        -------
        np.ndarray
            The points generated from the SVG file. Pass this to the FourierSeries constructor.
            Note that the points will be an array of complex numbers.

        Examples
        --------
        The following code generates a set of points from an SVG file and then animates it through a Fourier series.

        ```py
        points = FourierSeries.svg(r"path/to/file.svg")
        fs = FourierSeries(points)
        self.add(fs.mobject)
        ```
        """
        paths, _ = svg2paths(filename)

        return np.concatenate(
            [
                shape.points(np.linspace(0, 1, 100 * int(shape.length())))
                for path in paths
                for shape in path
            ]
        ).conjugate()

__init__(points, number=50, fade=0.005, circle_opacity=0.5, arrow_opacity=0.8, width=None, height=None, shift=0)

Initialize the FourierSeries object.

Parameters:

Name Type Description Default
points ndarray

The points to generate the Fourier series from. This can be generated from the text, image, or polygon static methods on this class.

required
number int

How many circles should be generated. The more circles, the more precise the output, but the longer time to render. By default 50

50
fade float

The rate at which the path should fade. The path exponentially fades by this amount each frame. By default 0.005

0.005
circle_opacity float

The opacity of the circles, by default 0.5

0.5
arrow_opacity float

The opacity of the arrows, by default 0.8

0.8
width int

The width of the window. If None, then this will occupy the entire window. The points will only be scaled uniformly. By default None

None
height int

The height of the window. If None, then this will occupy the entire window. The points will only be scaled uniformly. By default None

None
shift Optional[complex]

The amount to shift the points by. By default 0

0

Examples:

The following code animates a Fourier series for a nonagon.

points = FourierSeries.polygon(9)
fs = FourierSeries(points)
self.add(fs.mobject)

self.play(fs.revolve(1), run_time=5, rate_func=linear)
Source code in manim_fourier_series/main.py
def __init__(
    self,
    points: np.ndarray,
    number: int = 50,
    fade: float = 0.005,
    circle_opacity: float = 0.5,
    arrow_opacity: float = 0.8,
    width: Optional[int] = None,
    height: Optional[int] = None,
    shift: Optional[complex] = 0,
):
    """Initialize the FourierSeries object.

    Parameters
    ----------
    points : np.ndarray
        The points to generate the Fourier series from. This can be generated
        from the `text`, `image`, or `polygon` static methods on this class.
    number : int, optional
        How many circles should be generated. The more circles, the more precise the output, but the longer time to render. By default 50
    fade : float, optional
        The rate at which the path should fade. The path exponentially fades by this amount each frame. By default 0.005
    circle_opacity : float, optional
        The opacity of the circles, by default 0.5
    arrow_opacity : float, optional
        The opacity of the arrows, by default 0.8
    width : int, optional
        The width of the window. If None, then this will occupy the entire window. The points will only be scaled uniformly. By default None
    height : int, optional
        The height of the window. If None, then this will occupy the entire window. The points will only be scaled uniformly. By default None
    shift : Optional[complex], optional
        The amount to shift the points by. By default 0

    Examples
    --------
    The following code animates a Fourier series for a nonagon.

    ```py
    points = FourierSeries.polygon(9)
    fs = FourierSeries(points)
    self.add(fs.mobject)

    self.play(fs.revolve(1), run_time=5, rate_func=linear)
    ```
    """
    points = normalize(points, width=width, height=height) + shift

    self.points = points
    self.N = min(number, len(self.points))
    self.fade = fade

    self.amplitudes, self.frequencies, self.phases = fft(self.points, self.N)

    self.tracker = ValueTracker(0)

    self.arrows = [
        Arrow(
            ORIGIN,
            RIGHT,
            stroke_opacity=arrow_opacity,
            tip_style={
                "stroke_opacity": arrow_opacity,
                "fill_opacity": arrow_opacity,
            },
        )
        for _ in range(self.N)
    ]
    self.circles = [
        Circle(
            radius=self.amplitudes[i],
            color=TEAL,
            stroke_width=2,
            stroke_opacity=circle_opacity,
        )
        for i in range(self.N)
    ]

    self.path = NestedPath()

    self.values = ArrayMobject()
    self.cumulative = ArrayMobject()

    self.values.add_updater(
        lambda array, dt: array.set_data(
            np.array(
                [0]
                + [
                    a * np.exp(1j * (p + self.tracker.get_value() * f))
                    for a, f, p in zip(
                        self.amplitudes, self.frequencies, self.phases
                    )
                ]
            )
        ),  # This lambda sets the value to e^i(a + wt)
        call_updater=True,
    )
    self.cumulative.add_updater(
        lambda array, dt: array.become(self.values.sum()), call_updater=True
    )

    for i, (arrow, ring) in enumerate(zip(self.arrows, self.circles)):
        arrow.idx = i
        ring.idx = i
        ring.add_updater(
            lambda ring: ring.move_to(complex_to_R3(self.cumulative[ring.idx]))
        )
        arrow.add_updater(
            lambda arrow: arrow.become(
                Arrow(
                    complex_to_R3(self.cumulative[arrow.idx]),
                    complex_to_R3(self.cumulative[arrow.idx + 1]),
                    buff=0,
                    max_tip_length_to_length_ratio=0.2,
                    stroke_width=2,
                    stroke_opacity=arrow_opacity,
                    tip_style={
                        "stroke_opacity": arrow_opacity,
                        "fill_opacity": arrow_opacity,
                    },
                )
            )
        )

    self.path.set_points_as_corners([complex_to_R3(self.cumulative[-1])] * 2)
    self.path.add_updater(
        lambda path: path.updater(complex_to_R3(self.cumulative[-1]), self.fade)
    )

    self.mobject = Group(
        *self.arrows, *self.circles, self.values, self.cumulative, self.path
    )

display_complete_path(opacity=0.5)

Displays the entire path that the Fourier series will go through.

Parameters:

Name Type Description Default
opacity float

The opacity of the path, by default 0.5

0.5

Returns:

Type Description
FourierSeries

Self, for chaining purposes

Source code in manim_fourier_series/main.py
def display_complete_path(self, opacity: float = 0.5) -> FourierSeries:
    """Displays the entire path that the Fourier series will go through.

    Parameters
    ----------
    opacity : float, optional
        The opacity of the path, by default 0.5

    Returns
    -------
    FourierSeries
        Self, for chaining purposes
    """
    self.path.clear_updaters()
    self.path.set_points_as_corners([complex_to_R3(point) for point in self.points])
    self.path.set_stroke(opacity=opacity)
    return self

image(filename, greedy=False, remove_internal=True, multiple_contours=False) staticmethod

Generate a set of points from the edges of an image.

Parameters:

Name Type Description Default
filename str

Where the image is located.

required
greedy bool

This should normally be False, however if the image was rendered poorly, such as with peculiar lines, try setting this to True. By default False

False
remove_internal bool

Whether or not internal contours should be removed. In simple terms, when this is True, any paths that are within another path will not be rendered. For instance, an o would not have the interior line drawn, only the exterior. By default True

True
multiple_contours bool

Whether or not multiple contours are allowed. If this is False, only the contour occupying the largest area will be displayed. Note that this cannot be False when remove_internal is False. By default False

False

Returns:

Type Description
ndarray

The points generated from the image. Pass this to the FourierSeries constructor. Note that the points will be an array of complex numbers.

Examples:

The following code generates a set of points from an image of a bird and then animates it through a Fourier series.

points = FourierSeries.image(r"path/to/bird.jpg")
fs = FourierSeries(points)
self.add(fs.mobject)

Source code in manim_fourier_series/main.py
@staticmethod
def image(
    filename: str,
    greedy: bool = False,
    remove_internal: bool = True,
    multiple_contours: bool = False,
) -> np.ndarray:
    """Generate a set of points from the edges of an image.

    Parameters
    ----------
    filename : str
        Where the image is located.
    greedy : bool, optional
        This should normally be False, however if the image was rendered poorly, such as with
        peculiar lines, try setting this to True. By default False
    remove_internal : bool, optional
        Whether or not internal contours should be removed. In simple terms, when this
        is True, any paths that are within another path will not be rendered. For
        instance, an `o` would not have the interior line drawn, only the exterior.
        By default True
    multiple_contours : bool, optional
        Whether or not multiple contours are allowed. If this is False, only the contour
        occupying the largest area will be displayed. Note that this cannot be False
        when `remove_internal` is False. By default False

    Returns
    -------
    np.ndarray
        The points generated from the image. Pass this to the FourierSeries constructor.
        Note that the points will be an array of complex numbers.

    Examples
    --------

    The following code generates a set of points from an image of a bird and then animates it through a Fourier series.
    ```py
    points = FourierSeries.image(r"path/to/bird.jpg")
    fs = FourierSeries(points)
    self.add(fs.mobject)
    ```
    """
    image = cv2.imread(filename)

    scale = min(
        920 / image.shape[0], 1080 / image.shape[1]
    )  # Scale image to be no greater than 1080 x 920
    image = cv2.resize(
        image, (int(image.shape[1] * scale), int(image.shape[0] * scale))
    )

    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    image = 255 - cv2.adaptiveThreshold(
        image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2
    )  # Determine different areas

    contours, _ = cv2.findContours(
        image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
    )  # Find outlines of areas

    largest = max(contours, key=cv2.contourArea)  # Find the largest area

    image = np.zeros(
        image.shape, dtype=image.dtype
    )  # Shade everything that isn't the largest area

    cv2.drawContours(image, [largest], -1, (255, 255, 255), -1)

    if greedy:
        return extract_edges(
            image,
            greedy_shortest_path,
            remove_internal=remove_internal,
            multiple_contours=multiple_contours,
        )
    return extract_edges(
        image, remove_internal=remove_internal, multiple_contours=multiple_contours
    )

numpy_points(filename) staticmethod

Load a set of points from a numpy file.

Parameters:

Name Type Description Default
filename str

Where the numpy file is located.

required

Returns:

Type Description
ndarray

The points loaded from the numpy file. Pass this to the FourierSeries constructor. Note that the points will be an array of complex numbers.

Examples:

The following code loads a set of points from a numpy file and then animates it through a Fourier series.

points = FourierSeries.numpy_points(r"path/to/points.npy")
fs = FourierSeries(points)
self.add(fs.mobject)
Source code in manim_fourier_series/main.py
@staticmethod
def numpy_points(filename: str) -> np.ndarray:
    """Load a set of points from a numpy file.

    Parameters
    ----------
    filename : str
        Where the numpy file is located.

    Returns
    -------
    np.ndarray
        The points loaded from the numpy file. Pass this to the FourierSeries constructor.
        Note that the points will be an array of complex numbers.

    Examples
    --------
    The following code loads a set of points from a numpy file and then animates it through a Fourier series.

    ```py
    points = FourierSeries.numpy_points(r"path/to/points.npy")
    fs = FourierSeries(points)
    self.add(fs.mobject)
    ```
    """
    return np.load(filename)

polygon(n) staticmethod

Generate a set of points from a regular polygon.

Parameters:

Name Type Description Default
n int

The number of sides the polygon should have.

required

Returns:

Type Description
ndarray

The points generated from the polygon. Pass this to the FourierSeries constructor.

Examples:

The following code generates a set of points from a regular pentagon and then animates it through a Fourier series.

points = FourierSeries.polygon(5)
fs = FourierSeries(points)
self.add(fs.mobject)

self.play(fs.revolve(1), run_time=5, rate_func=linear)
Source code in manim_fourier_series/main.py
@staticmethod
def polygon(n: int) -> np.ndarray:
    """Generate a set of points from a regular polygon.

    Parameters
    ----------
    n : int
        The number of sides the polygon should have.

    Returns
    -------
    np.ndarray
        The points generated from the polygon. Pass this to the FourierSeries constructor.

    Examples
    --------
    The following code generates a set of points from a regular pentagon and then animates it through a Fourier series.

    ```py
    points = FourierSeries.polygon(5)
    fs = FourierSeries(points)
    self.add(fs.mobject)

    self.play(fs.revolve(1), run_time=5, rate_func=linear)
    ```
    """
    points = np.array(
        [
            np.linspace(
                np.exp(2j * k * np.pi / n), np.exp(2j * (k + 1) * np.pi / n), 1000
            )
            for k in range(n)
        ]
    ).reshape(-1)

    points *= 1j
    if not n % 2:
        points *= np.exp(1j * np.pi / n)
    return points

revolve(revolutions=1)

Animate the Fourier series.

Parameters:

Name Type Description Default
revolutions float

How many times the image should be drawn, by default 1

1

Returns:

Type Description
Animation

An animation that can be passed to self.play. A linear rate function is highly recommended.

Examples:

The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

points = FourierSeries.text("Guru", r"path/to/font.ttf")
fs = FourierSeries(points)
self.add(fs.mobject)

self.play(fs.revolve(1), run_time=5, rate_func=linear) # A linear rate function is highly recommended
Source code in manim_fourier_series/main.py
def revolve(self, revolutions: float = 1) -> Animation:
    """Animate the Fourier series.

    Parameters
    ----------
    revolutions : float, optional
        How many times the image should be drawn, by default 1

    Returns
    -------
    Animation
        An animation that can be passed to `self.play`. A linear rate function is highly recommended.

    Examples
    --------
    The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

    ```py
    points = FourierSeries.text("Guru", r"path/to/font.ttf")
    fs = FourierSeries(points)
    self.add(fs.mobject)

    self.play(fs.revolve(1), run_time=5, rate_func=linear) # A linear rate function is highly recommended
    ```
    """
    return self.tracker.animate.set_value(revolutions * 2 * np.pi)

svg(filename) staticmethod

Generate a set of points from an SVG file.

Parameters:

Name Type Description Default
filename str

Where the SVG file is located.

required

Returns:

Type Description
ndarray

The points generated from the SVG file. Pass this to the FourierSeries constructor. Note that the points will be an array of complex numbers.

Examples:

The following code generates a set of points from an SVG file and then animates it through a Fourier series.

points = FourierSeries.svg(r"path/to/file.svg")
fs = FourierSeries(points)
self.add(fs.mobject)
Source code in manim_fourier_series/main.py
@staticmethod
def svg(filename: str) -> np.ndarray:
    """Generate a set of points from an SVG file.

    Parameters
    ----------
    filename : str
        Where the SVG file is located.

    Returns
    -------
    np.ndarray
        The points generated from the SVG file. Pass this to the FourierSeries constructor.
        Note that the points will be an array of complex numbers.

    Examples
    --------
    The following code generates a set of points from an SVG file and then animates it through a Fourier series.

    ```py
    points = FourierSeries.svg(r"path/to/file.svg")
    fs = FourierSeries(points)
    self.add(fs.mobject)
    ```
    """
    paths, _ = svg2paths(filename)

    return np.concatenate(
        [
            shape.points(np.linspace(0, 1, 100 * int(shape.length())))
            for path in paths
            for shape in path
        ]
    ).conjugate()

text(text, font, remove_internal=True, multiple_contours=False) staticmethod

Generate a set of points from text.

Parameters:

Name Type Description Default
text str

The text to generate points from.

required
font str

A path to a font file, to be passed to PIL.ImageFont.truetype. A cursive font is highly recommended for multiple letters. Try Brush Script MT or similar.

required
remove_internal bool

Whether or not internal contours should be removed. In simple terms, when this is True, any paths that are within another path will not be rendered. For instance, an o would not have the interior line drawn, only the exterior. By default True

True
multiple_contours bool

Whether or not multiple contours are allowed. If this is False, only the contour occupying the largest area will be displayed. Note that this cannot be False when remove_internal is False. By default False

False

Returns:

Type Description
ndarray

The points generated from the text. Pass this to the FourierSeries constructor. Note that the points will be an array of complex numbers.

Examples:

The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

points = FourierSeries.text("Guru", r"path/to/font.ttf")
fs = FourierSeries(points)
self.add(fs.mobject)
Source code in manim_fourier_series/main.py
@staticmethod
def text(
    text: str,
    font: str,
    remove_internal: bool = True,
    multiple_contours: bool = False,
) -> np.ndarray:
    """Generate a set of points from text.

    Parameters
    ----------
    text : str
        The text to generate points from.
    font : str
        A path to a font file, to be passed to `PIL.ImageFont.truetype`. A cursive font
        is highly recommended for multiple letters. Try [Brush Script MT](https://github.com/PeculiarProgrammer/manim-fourier-series/raw/refs/heads/master/examples/fonts/brush.ttf) or similar.
    remove_internal : bool, optional
        Whether or not internal contours should be removed. In simple terms, when this
        is True, any paths that are within another path will not be rendered. For
        instance, an `o` would not have the interior line drawn, only the exterior.
        By default True
    multiple_contours : bool, optional
        Whether or not multiple contours are allowed. If this is False, only the contour
        occupying the largest area will be displayed. Note that this cannot be False
        when `remove_internal` is False. By default False

    Returns
    -------
    np.ndarray
        The points generated from the text. Pass this to the FourierSeries constructor.
        Note that the points will be an array of complex numbers.

    Examples
    --------
    The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

    ```py
    points = FourierSeries.text("Guru", r"path/to/font.ttf")
    fs = FourierSeries(points)
    self.add(fs.mobject)
    ```
    """
    font_file = ImageFont.truetype(font, size=1000)

    mask = font_file.getmask(text, mode="1")

    image = Image.frombytes(mask.mode, mask.size, bytes(mask))
    image = np.array(image)

    return extract_edges(
        image, greedy_shortest_path, False, remove_internal, multiple_contours
    )

zoomed_display(scene, animate=True, scale_factor=2)

Add a window to the scene that follows the path.

Parameters:

Name Type Description Default
scene ZoomedScene

The scene to add the window to. This must be a ZoomedScene otherwise the window will not work.

required
animate bool

Whether or not the window's entrance should be animated, by default True

True
scale_factor float

How much the zoomed camera should be scaled by. The smaller, the more zoomed in. By default 2

2

Returns:

Type Description
FourierSeries

Self, for chaining purposes

Raises:

Type Description
AssertionError

If the scene is not a ZoomedScene

Examples:

The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

class BasicExample(ZoomedScene):
    def construct(self):
        points = FourierSeries.text("Guru", r"path/to/font.ttf")

        fs = FourierSeries(points)
        self.add(fs.mobject)

        fs.zoomed_display(self)

        self.play(fs.revolve(1), run_time=5, rate_func=linear)
Source code in manim_fourier_series/main.py
def zoomed_display(
    self, scene: ZoomedScene, animate: bool = True, scale_factor: float = 2
) -> FourierSeries:
    """Add a window to the scene that follows the path.

    Parameters
    ----------
    scene : ZoomedScene
        The scene to add the window to. This must be a `ZoomedScene` otherwise the window will not work.
    animate : bool, optional
        Whether or not the window's entrance should be animated, by default True
    scale_factor : float, optional
        How much the zoomed camera should be scaled by. The smaller, the more zoomed in. By default 2

    Returns
    -------
    FourierSeries
        Self, for chaining purposes

    Raises
    ------
    AssertionError
        If the scene is not a `ZoomedScene`

    Examples
    --------
    The following code generates a set of points from the text "Guru" and then animates it through a Fourier series.

    ```py
    class BasicExample(ZoomedScene):
        def construct(self):
            points = FourierSeries.text("Guru", r"path/to/font.ttf")

            fs = FourierSeries(points)
            self.add(fs.mobject)

            fs.zoomed_display(self)

            self.play(fs.revolve(1), run_time=5, rate_func=linear)
    ```
    """
    assert isinstance(scene, ZoomedScene), "The scene must be a ZoomedScene"

    scene.zoomed_camera.frame.scale(scale_factor)
    scene.zoomed_camera.frame.move_to(complex_to_R3(self.cumulative[-1]))

    scene.activate_zooming(animate)

    scene.zoomed_camera.frame.add_updater(
        lambda frame: frame.move_to(complex_to_R3(self.cumulative[-1]))
    )

    return self

Documentation for NestedPath

Bases: VGroup

A Mobject that makes it easy to display points as a path.

Examples:

path = NestedPath()
path.set_points_as_corners([LEFT, RIGHT, UP, DOWN])
self.add(path)
Source code in manim_fourier_series/mobjects.py
class NestedPath(VGroup):  # Supports both OpenGL and Cairo backends
    """A Mobject that makes it easy to display points as a path.

    Examples
    --------

    ```py
    path = NestedPath()
    path.set_points_as_corners([LEFT, RIGHT, UP, DOWN])
    self.add(path)
    ```
    """

    def updater(self, point: np.ndarray, fade: float) -> NestedPath:
        previous_path = NestedPath()
        self.add(previous_path)

        previous_path.set_points_as_corners(self.points.copy())
        previous_path.add_updater(
            lambda path: (
                path.fade(fade)
                if path.get_stroke_opacity() > 2e-2
                else path.clear_updaters()
            )
        )

        self.add_points_as_corners([point])
        self.set_points_as_corners(self.points[-4:])

        return self

Documentation for ArrayMobject

Bases: Group

A dummy Mobject to store an array of data that updates each frame.

Source code in manim_fourier_series/mobjects.py
class ArrayMobject(Group):  # Supports both OpenGL and Cairo backends
    """A dummy Mobject to store an array of data that updates each frame."""

    def __init__(self, array: np.ndarray = None):
        super().__init__()

        self.set_data(array)

    def get_data(self) -> np.ndarray:
        """Get the data stored in the Mobject.

        Returns
        -------
        np.ndarray
            Returns the data stored in the Mobject.
        """
        return self.__data

    def set_data(self, data: np.ndarray) -> None:
        """Set the data stored in the Mobject.

        Parameters
        ----------
        data : np.ndarray
            The data to store in the Mobject.
        """
        self.__data = data

    def sum(self) -> ArrayMobject:
        """Accumulate the data and return a new Mobject.

        Returns
        -------
        ArrayMobject
            A new Mobject with the accumulated data.
        """
        return ArrayMobject(np.add.accumulate(self.get_data()))

    def __getitem__(self, idx: int) -> float:
        return self.get_data()[idx]

    def become(self, new_obj: ArrayMobject) -> ArrayMobject:
        """Set the data stored in the Mobject to the data stored in another
        Mobject.

        Parameters
        ----------
        new_obj : ArrayMobject
            The Mobject to copy the data from.

        Returns
        -------
        ArrayMobject
            Self, for chaining purposes.
        """
        self.set_data(new_obj.get_data())

        return self

become(new_obj)

Set the data stored in the Mobject to the data stored in another Mobject.

Parameters:

Name Type Description Default
new_obj ArrayMobject

The Mobject to copy the data from.

required

Returns:

Type Description
ArrayMobject

Self, for chaining purposes.

Source code in manim_fourier_series/mobjects.py
def become(self, new_obj: ArrayMobject) -> ArrayMobject:
    """Set the data stored in the Mobject to the data stored in another
    Mobject.

    Parameters
    ----------
    new_obj : ArrayMobject
        The Mobject to copy the data from.

    Returns
    -------
    ArrayMobject
        Self, for chaining purposes.
    """
    self.set_data(new_obj.get_data())

    return self

get_data()

Get the data stored in the Mobject.

Returns:

Type Description
ndarray

Returns the data stored in the Mobject.

Source code in manim_fourier_series/mobjects.py
def get_data(self) -> np.ndarray:
    """Get the data stored in the Mobject.

    Returns
    -------
    np.ndarray
        Returns the data stored in the Mobject.
    """
    return self.__data

set_data(data)

Set the data stored in the Mobject.

Parameters:

Name Type Description Default
data ndarray

The data to store in the Mobject.

required
Source code in manim_fourier_series/mobjects.py
def set_data(self, data: np.ndarray) -> None:
    """Set the data stored in the Mobject.

    Parameters
    ----------
    data : np.ndarray
        The data to store in the Mobject.
    """
    self.__data = data

sum()

Accumulate the data and return a new Mobject.

Returns:

Type Description
ArrayMobject

A new Mobject with the accumulated data.

Source code in manim_fourier_series/mobjects.py
def sum(self) -> ArrayMobject:
    """Accumulate the data and return a new Mobject.

    Returns
    -------
    ArrayMobject
        A new Mobject with the accumulated data.
    """
    return ArrayMobject(np.add.accumulate(self.get_data()))

Documentation for utils

extract_edges(image, shortest_path=self_organising_maps, subsample=True, remove_internal=True, multiple_contours=False)

Extract the edges from an image.

Parameters:

Name Type Description Default
image ndarray

The image to extract the edges from

required
shortest_path Callable[[ndarray], ndarray]

The algorithm to determine the path, by default self_organising_maps

self_organising_maps
subsample bool

Should points be sampled, by default True

True
remove_internal bool

Whether or not internal contours should be removed. In simple terms, when this is True, any paths that are within another path will not be rendered. For instance, an o would not have the interior line drawn, only the exterior. By default True

True
multiple_contours bool

Whether or not multiple contours are allowed. If this is False, only the contour occupying the largest area will be displayed. Note that this cannot be False when remove_internal is False. By default False

False

Returns:

Type Description
ndarray

The edges of the image

Source code in manim_fourier_series/utils.py
def extract_edges(
    image: np.ndarray,
    shortest_path: Callable[[np.ndarray], np.ndarray] = self_organising_maps,
    subsample=True,
    remove_internal=True,
    multiple_contours=False,
) -> np.ndarray:
    """Extract the edges from an image.

    Parameters
    ----------
    image : np.ndarray
        The image to extract the edges from
    shortest_path : Callable[[np.ndarray], np.ndarray], optional
        The algorithm to determine the path, by default self_organising_maps
    subsample : bool, optional
        Should points be sampled, by default True
    remove_internal : bool, optional
        Whether or not internal contours should be removed. In simple terms, when this
        is True, any paths that are within another path will not be rendered. For
        instance, an `o` would not have the interior line drawn, only the exterior.
        By default True
    multiple_contours : bool, optional
        Whether or not multiple contours are allowed. If this is False, only the contour
        occupying the largest area will be displayed. Note that this cannot be False
        when `remove_internal` is False. By default False

    Returns
    -------
    np.ndarray
        The edges of the image
    """
    contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    all_contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    if not remove_internal:
        if multiple_contours == False:
            logger.warning(
                "multiple_contours should be True if remove_internal is False. Value will be temporarily set to True"
            )
            multiple_contours = True  # Future-proofing
        contours = all_contours
    else:
        if len(contours) < len(all_contours):
            logger.info("Omitting internal contours")
        if not multiple_contours and len(contours) > 1:
            logger.info("Multiple exterior contours found, using the largest one")
            contours = [max(contours, key=cv2.contourArea)]

    points = np.concatenate(contours).reshape(
        -1, 2
    )  # Convert points to complex numbers
    points = points[:, 0] - 1j * points[:, 1]

    points, scale = normalize(points, True)

    if not subsample:
        scale = 0
    return shortest_path(points[:: max(int(scale / 10), 1)])

fft(points, n)

Perform a Fast Fourier Transform on the points.

Parameters:

Name Type Description Default
points ndarray

The points to transform

required
n int

The number of frequencies to keep

required

Returns:

Type Description
Tuple[ndarray, ndarray, ndarray]

The amplitudes, frequencies and phases of the Fourier transform

Source code in manim_fourier_series/utils.py
def fft(points: np.ndarray, n: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Perform a Fast Fourier Transform on the points.

    Parameters
    ----------
    points : np.ndarray
        The points to transform
    n : int
        The number of frequencies to keep

    Returns
    -------
    Tuple[np.ndarray, np.ndarray, np.ndarray]
        The amplitudes, frequencies and phases of the Fourier transform
    """
    coefficients = np.fft.fft(points, norm="forward")
    frequencies = np.fft.fftfreq(len(points), 1 / len(points))

    indices = np.argsort(-abs(coefficients))[:n]
    frequencies = frequencies[indices]
    coefficients = coefficients[indices]

    phases = np.angle(coefficients)
    amplitudes = abs(coefficients)

    return amplitudes, frequencies, phases

normalize(points, return_factor=False, width=None, height=None)

Normalize the points to fit within the frame.

Parameters:

Name Type Description Default
points ndarray

The points to normalize

required
return_factor bool

Whether or not the scale factor should be returned, by default False

False
width Optional[int]

How wide the frame should be. When None, it is the width of the Manim frame. By default None

None
height Optional[int]

How tall the frame should be. When None, it is the height of the Manim frame. By default None

None

Returns:

Type Description
Union[ndarray, Tuple[ndarray, float]]

The normalized points. If return_factor is True, a tuple is returned with the scale factor as the second element.

Source code in manim_fourier_series/utils.py
def normalize(
    points: np.ndarray,
    return_factor: bool = False,
    width: Optional[int] = None,
    height: Optional[int] = None,
) -> Union[np.ndarray, Tuple[np.ndarray, float]]:
    """Normalize the points to fit within the frame.

    Parameters
    ----------
    points : np.ndarray
        The points to normalize
    return_factor : bool, optional
        Whether or not the scale factor should be returned, by default False
    width : Optional[int], optional
        How wide the frame should be. When None, it is the width of the Manim frame. By default None
    height : Optional[int], optional
        How tall the frame should be. When None, it is the height of the Manim frame. By default None

    Returns
    -------
    Union[np.ndarray, Tuple[np.ndarray, float]]
        The normalized points. If return_factor is True, a tuple is returned with the scale factor as the second element.
    """
    if width is None:
        width = config.frame_width
    if height is None:
        height = config.frame_height

    scale = (
        max(
            (max(points.real) - min(points.real)) / width,
            (max(points.imag) - min(points.imag)) / height,
        )
        / 0.9
    )  # Determine scale factor such that all points fit within 90% of the frame

    points /= scale
    points -= (max(points.real) + min(points.real)) / 2 - (
        max(points.imag) + min(points.imag)
    ) / 2j

    if return_factor:
        return points, 1
    else:
        return points