beziervis 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
beziervis/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """beziervis - evaluate, manipulate and animate Bézier curves.
2
+
3
+ >>> import beziervis as bv
4
+ >>> pts = bv.points([[0, 0], [5, 10], [9, 7], [4, 3]], n=200)
5
+ >>> pts.shape
6
+ (200, 2)
7
+
8
+ The core needs only NumPy. ``pip install beziervis[fast]`` adds Numba
9
+ kernels, which are used automatically; ``pip install beziervis[anim]`` adds
10
+ matplotlib for :func:`animate`.
11
+ """
12
+
13
+ from .core import (
14
+ BERNSTEIN_MAX_DEGREE,
15
+ bernstein_matrix,
16
+ casteljau_steps,
17
+ get_backend,
18
+ numba_available,
19
+ points,
20
+ points_batch,
21
+ random_control_points,
22
+ set_backend,
23
+ )
24
+ from .ops import arc_length, derivative, elevate, split
25
+
26
+ __version__ = "1.0.0"
27
+
28
+ # BezierAnimation is resolved lazily by __getattr__ below.
29
+ __all__ = [
30
+ "BERNSTEIN_MAX_DEGREE",
31
+ "BezierAnimation", # pylint: disable=undefined-all-variable
32
+ "animate",
33
+ "arc_length",
34
+ "bernstein_matrix",
35
+ "casteljau_steps",
36
+ "derivative",
37
+ "elevate",
38
+ "get_backend",
39
+ "numba_available",
40
+ "points",
41
+ "points_batch",
42
+ "random_control_points",
43
+ "set_backend",
44
+ "split",
45
+ ]
46
+
47
+
48
+ def animate(ctrl, **kwargs):
49
+ """Build an animation of de Casteljau's construction (needs matplotlib).
50
+
51
+ See :class:`beziervis.BezierAnimation` for the options.
52
+ """
53
+ from .animation import BezierAnimation # pylint: disable=import-outside-toplevel
54
+
55
+ return BezierAnimation(ctrl, **kwargs)
56
+
57
+
58
+ def __getattr__(name):
59
+ # Lazy so that importing beziervis never imports matplotlib.
60
+ if name == "BezierAnimation":
61
+ from .animation import BezierAnimation # pylint: disable=import-outside-toplevel
62
+
63
+ return BezierAnimation
64
+ raise AttributeError(f"module 'beziervis' has no attribute {name!r}")
beziervis/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Allow ``python -m beziervis``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
beziervis/_numba.py ADDED
@@ -0,0 +1,72 @@
1
+ """Optional Numba kernels.
2
+
3
+ Only imported when the "numba" backend is active. Every kernel uses de
4
+ Casteljau's algorithm: under JIT the loops are cheap and the method stays
5
+ numerically stable at any degree.
6
+ """
7
+
8
+ import numpy as np
9
+ from numba import njit, prange
10
+
11
+ #: Use the parallel kernel once there are at least this many points to compute.
12
+ PARALLEL_THRESHOLD = 20_000
13
+
14
+
15
+ @njit(cache=True, fastmath=False)
16
+ def _eval_into(ctrl, t, out, work):
17
+ """Evaluate ``ctrl`` at scalar ``t`` and write the result into ``out``."""
18
+ k, d = ctrl.shape
19
+ for i in range(k):
20
+ for j in range(d):
21
+ work[i, j] = ctrl[i, j]
22
+ s = 1.0 - t
23
+ for level in range(1, k):
24
+ for i in range(k - level):
25
+ for j in range(d):
26
+ work[i, j] = s * work[i, j] + t * work[i + 1, j]
27
+ for j in range(d):
28
+ out[j] = work[0, j]
29
+
30
+
31
+ @njit(cache=True)
32
+ def points_serial(ctrl, t):
33
+ """Evaluate one curve at every ``t``, on one thread."""
34
+ out = np.empty((t.shape[0], ctrl.shape[1]))
35
+ work = np.empty_like(ctrl)
36
+ for i in range(t.shape[0]):
37
+ _eval_into(ctrl, t[i], out[i], work)
38
+ return out
39
+
40
+
41
+ @njit(cache=True, parallel=True)
42
+ def points_parallel(ctrl, t):
43
+ """Evaluate one curve at every ``t``, split across threads."""
44
+ out = np.empty((t.shape[0], ctrl.shape[1]))
45
+ for i in prange(t.shape[0]): # pylint: disable=not-an-iterable
46
+ work = np.empty_like(ctrl)
47
+ _eval_into(ctrl, t[i], out[i], work)
48
+ return out
49
+
50
+
51
+ @njit(cache=True, parallel=True)
52
+ def batch_parallel(curves, t):
53
+ """Evaluate ``m`` curves at every ``t``, one curve per thread task."""
54
+ m, k, d = curves.shape
55
+ out = np.empty((m, t.shape[0], d))
56
+ for c in prange(m): # pylint: disable=not-an-iterable
57
+ work = np.empty((k, d))
58
+ for i in range(t.shape[0]):
59
+ _eval_into(curves[c], t[i], out[c, i], work)
60
+ return out
61
+
62
+
63
+ def points(ctrl: np.ndarray, t: np.ndarray) -> np.ndarray:
64
+ """Evaluate one curve, picking the serial or parallel kernel by work size."""
65
+ if t.shape[0] * ctrl.shape[0] >= PARALLEL_THRESHOLD:
66
+ return points_parallel(ctrl, t)
67
+ return points_serial(ctrl, t)
68
+
69
+
70
+ def points_batch(curves: np.ndarray, t: np.ndarray) -> np.ndarray:
71
+ """Evaluate a batch of curves of equal degree; returns (m, n, d)."""
72
+ return batch_parallel(curves, t)
beziervis/animation.py ADDED
@@ -0,0 +1,244 @@
1
+ """Animate de Casteljau's construction of a 2-D Bézier curve (needs matplotlib).
2
+
3
+ >>> import beziervis as bv
4
+ >>> anim = bv.animate([[0, 0], [5, 10], [9, 7], [4, 3]], verbose=True)
5
+ >>> anim.save("curve.gif") # doctest: +SKIP
6
+ >>> anim.show() # doctest: +SKIP
7
+
8
+ In Jupyter, an animation that is the last expression in a cell is displayed
9
+ inline as an interactive player.
10
+
11
+ ``save`` and the Jupyter display draw on a plain
12
+ :class:`matplotlib.figure.Figure`, not through pyplot, so they work on
13
+ machines without a display. Only :meth:`BezierAnimation.show` uses pyplot.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from typing import Optional
20
+
21
+ import numpy as np
22
+
23
+ try:
24
+ import matplotlib
25
+ from matplotlib import animation as mpl_animation
26
+ from matplotlib.collections import LineCollection
27
+ from matplotlib.figure import Figure
28
+ except ImportError as exc: # pragma: no cover - exercised only without matplotlib
29
+ raise ImportError(
30
+ "beziervis.animation needs matplotlib; install it with: pip install beziervis[anim]"
31
+ ) from exc
32
+
33
+ from .core import ArrayLike, as_control_points, casteljau_steps, points
34
+
35
+ #: Above this many control points, point labels are off by default.
36
+ MAX_DEFAULT_LABELS = 10
37
+
38
+
39
+ def _level_colors(n_ctrl: int, cmap_name: str) -> list:
40
+ """Split one colormap across every segment of every construction level.
41
+
42
+ Level 0 (the control polygon) has ``n_ctrl - 1`` segments, level 1 has
43
+ ``n_ctrl - 2`` and so on, so each segment gets its own colour and the
44
+ levels read as a gradient.
45
+ """
46
+ n_segments = max(1, n_ctrl * (n_ctrl - 1) // 2)
47
+ palette = matplotlib.colormaps[cmap_name](np.linspace(0, 0.9, n_segments))
48
+ colors, start = [], 0
49
+ for level in range(n_ctrl):
50
+ count = n_ctrl - 1 - level
51
+ colors.append(palette[start:start + count])
52
+ start += count
53
+ return colors
54
+
55
+
56
+ def _label_prefix(level: int) -> str:
57
+ """Return the label letter for a construction level: A, B, ..., Z, L26, L27, ..."""
58
+ return chr(ord("A") + level) if level < 26 else f"L{level}"
59
+
60
+
61
+ class BezierAnimation: # pylint: disable=too-many-instance-attributes
62
+ """An animation of a 2-D Bézier curve being traced by de Casteljau's algorithm.
63
+
64
+ Parameters
65
+ ----------
66
+ ctrl : array_like, shape (k, 2)
67
+ Control points.
68
+ frames : int, default 100
69
+ Number of parameter values between 0 and 1, i.e. animation steps.
70
+ verbose : bool, default False
71
+ Also draw the intermediate construction lines at every level. Best
72
+ kept for curves with about 6 control points or fewer.
73
+ labels : bool, optional
74
+ Label each point (A0, A1, ... for control points; B0, ... for level 1).
75
+ Defaults to True for up to 10 control points.
76
+ fps : int, default 30
77
+ Playback speed.
78
+ hold : int, default 30
79
+ Extra frames that hold the finished curve before the animation loops.
80
+ size : int, default 600
81
+ Width and height of the figure in pixels.
82
+ cmap : str, default "viridis"
83
+ Matplotlib colormap for the construction lines.
84
+ title : str, optional
85
+ Figure title. Defaults to "Bézier curve (degree N)".
86
+ """
87
+
88
+ def __init__( # pylint: disable=too-many-arguments
89
+ self,
90
+ ctrl: ArrayLike,
91
+ frames: int = 100,
92
+ verbose: bool = False,
93
+ labels: Optional[bool] = None,
94
+ *,
95
+ fps: int = 30,
96
+ hold: int = 30,
97
+ size: int = 600,
98
+ cmap: str = "viridis",
99
+ title: Optional[str] = None,
100
+ ):
101
+ self.ctrl = as_control_points(ctrl)
102
+ if self.ctrl.shape[1] != 2:
103
+ raise ValueError(
104
+ f"animate() draws 2-D curves; got {self.ctrl.shape[1]}-D control points"
105
+ )
106
+ if frames < 2:
107
+ raise ValueError(f"frames must be at least 2; got {frames}")
108
+ if fps < 1 or hold < 0 or size < 50:
109
+ raise ValueError("need fps >= 1, hold >= 0 and size >= 50")
110
+ self.frames = int(frames)
111
+ self.verbose = bool(verbose)
112
+ self.labels = (
113
+ len(self.ctrl) <= MAX_DEFAULT_LABELS if labels is None else bool(labels)
114
+ )
115
+ self.fps = int(fps)
116
+ self.hold = int(hold)
117
+ self.size = int(size)
118
+ self.cmap = cmap
119
+ self.title = title or f"Bézier curve (degree {len(self.ctrl) - 1})"
120
+ self.t = np.linspace(0.0, 1.0, self.frames)
121
+ self.curve = points(self.ctrl, t=self.t)
122
+ self.animation: Optional[mpl_animation.FuncAnimation] = None
123
+
124
+ # ------------------------------------------------------------------ building
125
+
126
+ def _limits(self):
127
+ """Square limits around the control points (the curve stays inside their hull)."""
128
+ lo, hi = self.ctrl.min(axis=0), self.ctrl.max(axis=0)
129
+ center = (lo + hi) / 2
130
+ half = float(np.max(hi - lo)) / 2 * 1.12
131
+ if half < 1e-9: # all control points coincide
132
+ half = 1.0
133
+ return (center[0] - half, center[0] + half), (center[1] - half, center[1] + half)
134
+
135
+ def _draw_level(self, ax, pts, colors, level, zorder):
136
+ """Draw one construction level; return its (lines, markers, texts)."""
137
+ lines = LineCollection(
138
+ np.stack([pts[:-1], pts[1:]], axis=1), colors=colors, linewidths=1.5,
139
+ alpha=0.8, zorder=zorder,
140
+ )
141
+ ax.add_collection(lines)
142
+ marker_color = colors[0] if len(colors) else "0.3"
143
+ (markers,) = ax.plot(*pts.T, "o", ms=4, color=marker_color, zorder=zorder + 0.1)
144
+ texts = []
145
+ if self.labels:
146
+ prefix = _label_prefix(level)
147
+ texts = [
148
+ ax.annotate(f"{prefix}{i}", p, xytext=(4, 4), textcoords="offset points",
149
+ fontsize=9, color="0.2", zorder=zorder + 0.2)
150
+ for i, p in enumerate(pts)
151
+ ]
152
+ return lines, markers, texts
153
+
154
+ def _build(self, fig) -> mpl_animation.FuncAnimation: # pylint: disable=too-many-locals
155
+ ax = fig.add_subplot()
156
+ fig.suptitle(self.title, fontsize=16)
157
+ xlim, ylim = self._limits()
158
+ ax.set_xlim(*xlim)
159
+ ax.set_ylim(*ylim)
160
+ ax.set_aspect("equal", adjustable="box")
161
+ ax.grid(True, alpha=0.25)
162
+
163
+ n_ctrl = len(self.ctrl)
164
+ colors = _level_colors(n_ctrl, self.cmap)
165
+ self._draw_level(ax, self.ctrl, colors[0], 0, zorder=2)
166
+
167
+ # Intermediate levels 1 .. k-2 (level k-1 is the single traced point).
168
+ dynamic = []
169
+ if self.verbose:
170
+ steps = casteljau_steps(self.ctrl, 0.0)
171
+ for level in range(1, n_ctrl - 1):
172
+ dynamic.append(self._draw_level(ax, steps[level], colors[level], level, 3))
173
+
174
+ (trace,) = ax.plot([], [], color="black", lw=2, label="Bézier curve", zorder=4)
175
+ (head,) = ax.plot([], [], "o", color="crimson", ms=7, zorder=5)
176
+ ax.legend(loc="upper right")
177
+
178
+ last = self.frames - 1
179
+
180
+ def update(frame):
181
+ i = min(frame, last)
182
+ trace.set_data(self.curve[: i + 1, 0], self.curve[: i + 1, 1])
183
+ head.set_data(self.curve[i : i + 1, 0], self.curve[i : i + 1, 1])
184
+ if dynamic:
185
+ steps = casteljau_steps(self.ctrl, self.t[i])
186
+ visible = i < last # at t = 1 every level collapses onto the end point
187
+ for level, (lines, markers, texts) in enumerate(dynamic, start=1):
188
+ pts = steps[level]
189
+ lines.set_segments(np.stack([pts[:-1], pts[1:]], axis=1))
190
+ markers.set_data(pts[:, 0], pts[:, 1])
191
+ for text, p in zip(texts, pts):
192
+ text.xy = p
193
+ for artist in (lines, markers, *texts):
194
+ artist.set_visible(visible)
195
+ return []
196
+
197
+ update(0)
198
+ return mpl_animation.FuncAnimation(
199
+ fig, update, frames=self.frames + self.hold, interval=1000 / self.fps,
200
+ blit=False, repeat=True, cache_frame_data=False,
201
+ )
202
+
203
+ def _offscreen(self) -> mpl_animation.FuncAnimation:
204
+ fig = Figure(figsize=(self.size / 100, self.size / 100), dpi=100)
205
+ self.animation = self._build(fig)
206
+ return self.animation
207
+
208
+ # ------------------------------------------------------------------ output
209
+
210
+ def save(self, path: str, dpi: int = 100) -> str:
211
+ """Save as ``.gif`` (Pillow) or ``.mp4`` (needs ffmpeg). Returns ``path``."""
212
+ ext = os.path.splitext(path)[1].lower()
213
+ if ext == ".gif":
214
+ writer = mpl_animation.PillowWriter(fps=self.fps)
215
+ elif ext == ".mp4":
216
+ if not mpl_animation.writers.is_available("ffmpeg"):
217
+ raise RuntimeError("saving .mp4 needs ffmpeg on PATH; save a .gif instead")
218
+ writer = mpl_animation.FFMpegWriter(fps=self.fps)
219
+ else:
220
+ raise ValueError(f"unsupported file type {ext!r}; use .gif or .mp4")
221
+ self._offscreen().save(path, writer=writer, dpi=dpi)
222
+ return path
223
+
224
+ def to_jshtml(self) -> str:
225
+ """Return the animation as a self-contained HTML/JavaScript player."""
226
+ return self._offscreen().to_jshtml(fps=self.fps)
227
+
228
+ def _repr_html_(self) -> str:
229
+ return self.to_jshtml()
230
+
231
+ def show(self) -> "BezierAnimation":
232
+ """Open the animation in an interactive matplotlib window."""
233
+ import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel
234
+
235
+ fig = plt.figure(figsize=(self.size / 100, self.size / 100), dpi=100)
236
+ self.animation = self._build(fig)
237
+ plt.show()
238
+ return self
239
+
240
+ def __repr__(self) -> str:
241
+ return (
242
+ f"BezierAnimation(degree={len(self.ctrl) - 1}, frames={self.frames}, "
243
+ f"verbose={self.verbose})"
244
+ )
beziervis/cli.py ADDED
@@ -0,0 +1,94 @@
1
+ """Command-line interface: ``beziervis`` (or ``python -m beziervis``).
2
+
3
+ Examples::
4
+
5
+ beziervis --points "0,0 5,10 9,7 4,3" --verbose --save curve.gif
6
+ beziervis -n 5 --seed 42
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import sys
13
+ from typing import List, Optional
14
+
15
+ import numpy as np
16
+
17
+ from . import __version__
18
+ from .core import random_control_points
19
+
20
+
21
+ def parse_points(text: str) -> np.ndarray:
22
+ """Parse ``"x0,y0 x1,y1 ..."`` into a (k, 2) array."""
23
+ try:
24
+ pts = [[float(v) for v in pair.split(",")] for pair in text.split()]
25
+ except ValueError as exc:
26
+ raise argparse.ArgumentTypeError(f"could not parse points {text!r}: {exc}") from exc
27
+ if not pts:
28
+ raise argparse.ArgumentTypeError("no points given")
29
+ if any(len(p) != 2 for p in pts):
30
+ raise argparse.ArgumentTypeError(
31
+ f"each point must be 'x,y' with points separated by spaces; got {text!r}"
32
+ )
33
+ return np.array(pts)
34
+
35
+
36
+ def build_parser() -> argparse.ArgumentParser:
37
+ """Return the argument parser."""
38
+ parser = argparse.ArgumentParser(
39
+ prog="beziervis",
40
+ description="Animate a Bézier curve being built by de Casteljau's algorithm.",
41
+ epilog='Example: beziervis --points "0,0 5,10 9,7 4,3" --verbose --save curve.gif',
42
+ )
43
+ src = parser.add_mutually_exclusive_group()
44
+ src.add_argument("--points", "-p", type=parse_points, metavar='"x,y x,y ..."',
45
+ help="control points, space-separated")
46
+ src.add_argument("-n", type=int, default=4, metavar="N",
47
+ help="number of random control points (default: 4)")
48
+ parser.add_argument("--seed", type=int, help="random seed, for reproducible points")
49
+ parser.add_argument("-f", "--frames", type=int, default=100,
50
+ help="number of animation steps (default: 100)")
51
+ parser.add_argument("--fps", type=int, default=30, help="frames per second (default: 30)")
52
+ parser.add_argument("-v", "--verbose", action="store_true",
53
+ help="draw the intermediate construction lines")
54
+ parser.add_argument("--no-labels", action="store_true", help="hide point labels")
55
+ parser.add_argument("--size", type=int, default=600,
56
+ help="figure size in pixels (default: 600)")
57
+ parser.add_argument("-s", "--save", metavar="FILE",
58
+ help="save to .gif or .mp4 instead of opening a window")
59
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
60
+ return parser
61
+
62
+
63
+ def main(argv: Optional[List[str]] = None) -> int:
64
+ """Entry point. Returns the process exit code."""
65
+ parser = build_parser()
66
+ args = parser.parse_args(argv)
67
+ if args.points is None and args.n < 1:
68
+ parser.error("-n must be at least 1")
69
+
70
+ try:
71
+ from .animation import BezierAnimation # pylint: disable=import-outside-toplevel
72
+ except ImportError as exc:
73
+ print(f"beziervis: {exc}", file=sys.stderr)
74
+ return 1
75
+
76
+ ctrl = args.points if args.points is not None else random_control_points(args.n, args.seed)
77
+ try:
78
+ anim = BezierAnimation(
79
+ ctrl, frames=args.frames, verbose=args.verbose,
80
+ labels=False if args.no_labels else None, fps=args.fps, size=args.size,
81
+ )
82
+ if args.save:
83
+ anim.save(args.save)
84
+ print(f"saved {args.save}")
85
+ else:
86
+ anim.show()
87
+ except (ValueError, RuntimeError) as exc:
88
+ print(f"beziervis: {exc}", file=sys.stderr)
89
+ return 2
90
+ return 0
91
+
92
+
93
+ if __name__ == "__main__": # pragma: no cover
94
+ sys.exit(main())
beziervis/core.py ADDED
@@ -0,0 +1,258 @@
1
+ """NumPy evaluation core and backend selection.
2
+
3
+ Two evaluation strategies are implemented here:
4
+
5
+ * **Bernstein matrix** - build the ``(n, k)`` matrix of Bernstein basis values
6
+ once and evaluate every point with a single matrix multiply. This is the
7
+ fastest option for low and moderate degrees.
8
+ * **Vectorised de Casteljau** - repeated linear interpolation, applied to all
9
+ parameter values at once. Slower, but numerically stable at any degree, so
10
+ it is used above :data:`BERNSTEIN_MAX_DEGREE`.
11
+
12
+ If Numba is installed, :func:`points` and :func:`points_batch` dispatch to the
13
+ JIT kernels in :mod:`beziervis._numba` instead. Set the environment variable
14
+ ``BEZIERVIS_BACKEND`` to ``numpy``, ``numba`` or ``auto`` (the default) to
15
+ force a choice at import time, or call :func:`set_backend` at runtime.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from math import comb
22
+ from typing import List, Optional, Sequence, Union
23
+
24
+ import numpy as np
25
+
26
+ ArrayLike = Union[np.ndarray, Sequence[Sequence[float]]]
27
+
28
+ #: Highest degree evaluated with the Bernstein matrix; above it, de Casteljau.
29
+ BERNSTEIN_MAX_DEGREE = 30
30
+
31
+ #: Name of the environment variable that forces a backend.
32
+ BACKEND_ENV_VAR = "BEZIERVIS_BACKEND"
33
+
34
+ _BACKENDS = ("auto", "numpy", "numba")
35
+ _backend: str = "numpy"
36
+
37
+
38
+ # =============================================================================
39
+ # Backend selection
40
+ # =============================================================================
41
+
42
+ def numba_available() -> bool:
43
+ """Return True if Numba can be imported."""
44
+ try:
45
+ import numba # noqa: F401 pylint: disable=import-outside-toplevel,unused-import
46
+ except ImportError:
47
+ return False
48
+ return True
49
+
50
+
51
+ def set_backend(name: str = "auto") -> str:
52
+ """Select the evaluation backend and return the name actually in use.
53
+
54
+ Parameters
55
+ ----------
56
+ name : {"auto", "numpy", "numba"}
57
+ ``"auto"`` picks Numba when it is installed and NumPy otherwise.
58
+ ``"numba"`` raises :class:`ImportError` if Numba is not installed.
59
+ """
60
+ global _backend # pylint: disable=global-statement
61
+ name = name.strip().lower()
62
+ if name not in _BACKENDS:
63
+ raise ValueError(f"unknown backend {name!r}; expected one of {_BACKENDS}")
64
+ if name == "auto":
65
+ name = "numba" if numba_available() else "numpy"
66
+ elif name == "numba" and not numba_available():
67
+ raise ImportError(
68
+ "the 'numba' backend was requested but Numba is not installed; "
69
+ "install it with: pip install beziervis[fast]"
70
+ )
71
+ _backend = name
72
+ return _backend
73
+
74
+
75
+ def get_backend() -> str:
76
+ """Return the name of the backend currently in use ("numpy" or "numba")."""
77
+ return _backend
78
+
79
+
80
+ # =============================================================================
81
+ # Input handling
82
+ # =============================================================================
83
+
84
+ def as_control_points(ctrl: ArrayLike) -> np.ndarray:
85
+ """Convert control points to a C-contiguous float64 array of shape (k, d).
86
+
87
+ ``k`` is the number of control points (degree + 1) and ``d`` the spatial
88
+ dimension. A one-dimensional curve must be given as shape ``(k, 1)``.
89
+ """
90
+ arr = np.ascontiguousarray(ctrl, dtype=np.float64)
91
+ if arr.ndim != 2:
92
+ raise ValueError(
93
+ f"control points must have shape (k, d); got an array with shape {arr.shape}"
94
+ )
95
+ if arr.shape[0] < 1 or arr.shape[1] < 1:
96
+ raise ValueError(f"need at least one control point of dimension >= 1; got {arr.shape}")
97
+ if not np.all(np.isfinite(arr)):
98
+ raise ValueError("control points must be finite")
99
+ return arr
100
+
101
+
102
+ def _as_batch(curves: ArrayLike) -> np.ndarray:
103
+ arr = np.ascontiguousarray(curves, dtype=np.float64)
104
+ if arr.ndim != 3 or 0 in arr.shape:
105
+ raise ValueError(
106
+ "curves must have shape (m, k, d): m curves of k control points each; "
107
+ f"got {arr.shape}"
108
+ )
109
+ if not np.all(np.isfinite(arr)):
110
+ raise ValueError("control points must be finite")
111
+ return arr
112
+
113
+
114
+ def parameter_values(n: int = 100, t: Optional[ArrayLike] = None) -> np.ndarray:
115
+ """Return parameter values: ``t`` if given, else ``n`` evenly spaced in [0, 1]."""
116
+ if t is not None:
117
+ arr = np.ascontiguousarray(t, dtype=np.float64)
118
+ if arr.ndim == 0:
119
+ arr = arr.reshape(1)
120
+ if arr.ndim != 1:
121
+ raise ValueError(f"t must be a scalar or 1-D array; got shape {arr.shape}")
122
+ return arr
123
+ if int(n) != n or n < 1:
124
+ raise ValueError(f"n must be a positive integer; got {n!r}")
125
+ return np.linspace(0.0, 1.0, int(n))
126
+
127
+
128
+ # =============================================================================
129
+ # NumPy kernels
130
+ # =============================================================================
131
+
132
+ def bernstein_matrix(degree: int, t: np.ndarray) -> np.ndarray:
133
+ """Return the ``(len(t), degree + 1)`` matrix of Bernstein basis values."""
134
+ i = np.arange(degree + 1)
135
+ coeffs = np.array([comb(degree, j) for j in i], dtype=np.float64)
136
+ t = np.asarray(t, dtype=np.float64)[:, None]
137
+ return coeffs * t**i * (1.0 - t) ** (degree - i)
138
+
139
+
140
+ def casteljau_numpy(ctrl: np.ndarray, t: np.ndarray) -> np.ndarray:
141
+ """Evaluate with de Casteljau's algorithm, vectorised over ``t``."""
142
+ work = np.broadcast_to(ctrl, (t.shape[0],) + ctrl.shape)
143
+ tt = t[:, None, None]
144
+ st = 1.0 - tt
145
+ for _ in range(ctrl.shape[0] - 1):
146
+ work = st * work[:, :-1] + tt * work[:, 1:]
147
+ return np.ascontiguousarray(work[:, 0])
148
+
149
+
150
+ def points_numpy(ctrl: np.ndarray, t: np.ndarray) -> np.ndarray:
151
+ """Evaluate one curve with NumPy, choosing the method by degree."""
152
+ degree = ctrl.shape[0] - 1
153
+ if degree <= BERNSTEIN_MAX_DEGREE:
154
+ return bernstein_matrix(degree, t) @ ctrl
155
+ return casteljau_numpy(ctrl, t)
156
+
157
+
158
+ def points_batch_numpy(curves: np.ndarray, t: np.ndarray) -> np.ndarray:
159
+ """Evaluate ``m`` curves of equal degree with NumPy; returns (m, n, d)."""
160
+ degree = curves.shape[1] - 1
161
+ if degree <= BERNSTEIN_MAX_DEGREE:
162
+ return np.einsum("nk,mkd->mnd", bernstein_matrix(degree, t), curves)
163
+ return np.stack([casteljau_numpy(c, t) for c in curves])
164
+
165
+
166
+ # =============================================================================
167
+ # Public API
168
+ # =============================================================================
169
+
170
+ def points(ctrl: ArrayLike, n: int = 100, t: Optional[ArrayLike] = None) -> np.ndarray:
171
+ """Evaluate a Bézier curve.
172
+
173
+ Parameters
174
+ ----------
175
+ ctrl : array_like, shape (k, d)
176
+ Control points; a list of lists works. Any dimension ``d``.
177
+ n : int, default 100
178
+ Number of evenly spaced samples in [0, 1], including both end points.
179
+ Ignored when ``t`` is given.
180
+ t : array_like, optional
181
+ Explicit parameter values to evaluate at.
182
+
183
+ Returns
184
+ -------
185
+ numpy.ndarray, shape (n, d)
186
+ Points on the curve. The first row is ``ctrl[0]`` and the last is
187
+ ``ctrl[-1]``.
188
+
189
+ Examples
190
+ --------
191
+ >>> import beziervis as bv
192
+ >>> bv.points([[0, 0], [1, 2], [2, 0]], n=3)
193
+ array([[0., 0.],
194
+ [1., 1.],
195
+ [2., 0.]])
196
+ """
197
+ ctrl = as_control_points(ctrl)
198
+ tv = parameter_values(n, t)
199
+ if _backend == "numba":
200
+ from . import _numba # pylint: disable=import-outside-toplevel
201
+ return _numba.points(ctrl, tv)
202
+ return points_numpy(ctrl, tv)
203
+
204
+
205
+ def points_batch(curves: ArrayLike, n: int = 100, t: Optional[ArrayLike] = None) -> np.ndarray:
206
+ """Evaluate many curves of the same degree at once.
207
+
208
+ Parameters
209
+ ----------
210
+ curves : array_like, shape (m, k, d)
211
+ ``m`` curves with ``k`` control points each.
212
+ n, t
213
+ As in :func:`points`.
214
+
215
+ Returns
216
+ -------
217
+ numpy.ndarray, shape (m, n, d)
218
+ """
219
+ arr = _as_batch(curves)
220
+ tv = parameter_values(n, t)
221
+ if _backend == "numba":
222
+ from . import _numba # pylint: disable=import-outside-toplevel
223
+ return _numba.points_batch(arr, tv)
224
+ return points_batch_numpy(arr, tv)
225
+
226
+
227
+ def casteljau_steps(ctrl: ArrayLike, t: float) -> List[np.ndarray]:
228
+ """Return every level of de Casteljau's construction at parameter ``t``.
229
+
230
+ Level 0 is the control polygon, of shape ``(k, d)``. Each later level
231
+ interpolates between neighbouring points of the previous one, so level
232
+ ``j`` has shape ``(k - j, d)``. The final level holds a single point: the
233
+ curve evaluated at ``t``.
234
+ """
235
+ level = as_control_points(ctrl)
236
+ t = float(t)
237
+ steps = [level]
238
+ while level.shape[0] > 1:
239
+ level = (1.0 - t) * level[:-1] + t * level[1:]
240
+ steps.append(level)
241
+ return steps
242
+
243
+
244
+ def random_control_points(
245
+ n: int,
246
+ seed: Optional[int] = None,
247
+ low: float = -100.0,
248
+ high: float = 100.0,
249
+ dim: int = 2,
250
+ ) -> np.ndarray:
251
+ """Return ``n`` random integer-valued control points in ``[low, high)``."""
252
+ if n < 1:
253
+ raise ValueError(f"n must be at least 1; got {n}")
254
+ rng = np.random.default_rng(seed)
255
+ return rng.integers(int(low), int(high), size=(n, dim)).astype(np.float64)
256
+
257
+
258
+ set_backend(os.environ.get(BACKEND_ENV_VAR) or "auto")
beziervis/ops.py ADDED
@@ -0,0 +1,76 @@
1
+ """Operations on Bézier curves that return new control points or measurements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Tuple
6
+
7
+ import numpy as np
8
+
9
+ from .core import ArrayLike, as_control_points, casteljau_steps
10
+
11
+ _GL_NODES, _GL_WEIGHTS = np.polynomial.legendre.leggauss(16)
12
+
13
+
14
+ def split(ctrl: ArrayLike, t: float = 0.5) -> Tuple[np.ndarray, np.ndarray]:
15
+ """Split a curve at ``t`` into two curves of the same degree.
16
+
17
+ Returns ``(left, right)``: ``left`` traces the original over ``[0, t]``
18
+ and ``right`` over ``[t, 1]``, each reparameterised to ``[0, 1]``.
19
+ """
20
+ steps = casteljau_steps(ctrl, t)
21
+ left = np.array([level[0] for level in steps])
22
+ right = np.array([level[-1] for level in reversed(steps)])
23
+ return left, right
24
+
25
+
26
+ def derivative(ctrl: ArrayLike) -> np.ndarray:
27
+ """Return the control points of the derivative (hodograph) curve.
28
+
29
+ A degree-``n`` curve has a degree-``n - 1`` derivative with control points
30
+ ``n * (P[i+1] - P[i])``. The derivative of a single point (degree 0) is the
31
+ zero vector, returned as one control point.
32
+ """
33
+ ctrl = as_control_points(ctrl)
34
+ degree = ctrl.shape[0] - 1
35
+ if degree == 0:
36
+ return np.zeros_like(ctrl)
37
+ return degree * np.diff(ctrl, axis=0)
38
+
39
+
40
+ def elevate(ctrl: ArrayLike, times: int = 1) -> np.ndarray:
41
+ """Raise the degree by ``times`` without changing the shape of the curve."""
42
+ ctrl = as_control_points(ctrl)
43
+ if times < 0:
44
+ raise ValueError(f"times must be non-negative; got {times}")
45
+ for _ in range(times):
46
+ n = ctrl.shape[0] # new degree is n
47
+ alpha = (np.arange(1, n) / n)[:, None]
48
+ middle = alpha * ctrl[:-1] + (1.0 - alpha) * ctrl[1:]
49
+ ctrl = np.vstack([ctrl[:1], middle, ctrl[-1:]])
50
+ return ctrl
51
+
52
+
53
+ def arc_length(ctrl: ArrayLike, segments: int | None = None) -> float:
54
+ """Return the length of the curve.
55
+
56
+ Integrates the speed ``|B'(t)|`` with composite 16-point Gauss-Legendre
57
+ quadrature over ``segments`` equal pieces of [0, 1]. The default,
58
+ ``max(8, 4 * degree)``, is accurate to around 1e-10 for typical curves;
59
+ increase it for curves with cusps or very sharp turns.
60
+ """
61
+ from .core import points # pylint: disable=import-outside-toplevel
62
+
63
+ ctrl = as_control_points(ctrl)
64
+ degree = ctrl.shape[0] - 1
65
+ if degree == 0:
66
+ return 0.0
67
+ if segments is None:
68
+ segments = max(8, 4 * degree)
69
+ if segments < 1:
70
+ raise ValueError(f"segments must be at least 1; got {segments}")
71
+ edges = np.linspace(0.0, 1.0, segments + 1)
72
+ half = np.diff(edges)[:, None] / 2.0
73
+ mid = (edges[:-1] + edges[1:])[:, None] / 2.0
74
+ t = (mid + half * _GL_NODES).ravel()
75
+ speed = np.linalg.norm(points(derivative(ctrl), t=t), axis=1)
76
+ return float(np.sum((half * _GL_WEIGHTS).ravel() * speed))
@@ -0,0 +1,209 @@
1
+ Metadata-Version: 2.5
2
+ Name: beziervis
3
+ Version: 1.0.0
4
+ Summary: Fast Bézier curve evaluation in NumPy, with animations of de Casteljau's algorithm.
5
+ Project-URL: Homepage, https://github.com/venkateshwara-gopisetti/Bezier-Curves
6
+ Project-URL: Issues, https://github.com/venkateshwara-gopisetti/Bezier-Curves/issues
7
+ Author: Venkateshwara Gopisetti
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: animation,bezier,bezier-curve,de-casteljau,geometry,numba,numpy,visualization
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Multimedia :: Graphics
21
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
22
+ Classifier: Topic :: Scientific/Engineering :: Visualization
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: numpy>=1.23
25
+ Provides-Extra: all
26
+ Requires-Dist: matplotlib>=3.6; extra == 'all'
27
+ Requires-Dist: numba>=0.59; extra == 'all'
28
+ Requires-Dist: pillow>=9; extra == 'all'
29
+ Provides-Extra: anim
30
+ Requires-Dist: matplotlib>=3.6; extra == 'anim'
31
+ Requires-Dist: pillow>=9; extra == 'anim'
32
+ Provides-Extra: dev
33
+ Requires-Dist: matplotlib>=3.6; extra == 'dev'
34
+ Requires-Dist: numba>=0.59; extra == 'dev'
35
+ Requires-Dist: pillow>=9; extra == 'dev'
36
+ Requires-Dist: pylint>=3; extra == 'dev'
37
+ Requires-Dist: pytest>=7; extra == 'dev'
38
+ Provides-Extra: fast
39
+ Requires-Dist: numba>=0.59; extra == 'fast'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # beziervis
43
+
44
+ **Watch a Bézier curve build itself, and evaluate millions of curve points with a fast NumPy core.**
45
+
46
+ [![Tests](https://github.com/venkateshwara-gopisetti/Bezier-Curves/actions/workflows/tests.yml/badge.svg)](https://github.com/venkateshwara-gopisetti/Bezier-Curves/actions/workflows/tests.yml)
47
+ [![PyPI](https://img.shields.io/pypi/v/beziervis.svg)](https://pypi.org/project/beziervis/)
48
+ [![Python](https://img.shields.io/pypi/pyversions/beziervis.svg)](https://pypi.org/project/beziervis/)
49
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/LICENSE)
50
+ [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/quickstart.ipynb)
51
+
52
+ <p align="center">
53
+ <img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/hero.gif" width="480" alt="Animation of de Casteljau's algorithm tracing a degree-4 Bézier curve">
54
+ </p>
55
+
56
+ - **For learning:** animate de Casteljau's algorithm level by level, then save it as a GIF or MP4 or play it inline in Jupyter.
57
+ - **For computing:** evaluate curves of any degree, in any dimension, singly or in batches of thousands. Under the hood this is a Bernstein-matrix NumPy core, with optional Numba kernels for a further 3–40× speed-up.
58
+ - **Small:** the only required dependency is NumPy. Animation and acceleration are opt-in extras.
59
+
60
+ [Quickstart notebook](https://colab.research.google.com/github/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/quickstart.ipynb) · [Gallery](#gallery) · [API](#api) · [CLI](#command-line) · [How it works](#how-de-casteljaus-algorithm-works) · [Performance](#performance) · [Contributing](https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/CONTRIBUTING.md) · [Changelog](https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/CHANGELOG.md)
61
+
62
+ ## Install
63
+
64
+ ```bash
65
+ pip install beziervis # core: NumPy only
66
+ pip install "beziervis[all]" # + Numba acceleration and matplotlib animations
67
+ ```
68
+
69
+ | extra | adds | for |
70
+ |---|---|---|
71
+ | `[anim]` | matplotlib, Pillow | `animate()` and the `beziervis` command |
72
+ | `[fast]` | Numba | JIT and multi-threaded evaluation, used automatically |
73
+ | `[all]` | both | everything |
74
+
75
+ Requires Python 3.10 or newer. Tested on Linux, macOS and Windows.
76
+
77
+ ## Quickstart
78
+
79
+ ```python
80
+ import beziervis as bv
81
+
82
+ ctrl = [[0, 0], [5, 10], [9, 7], [4, 3]] # 4 control points -> a cubic curve
83
+
84
+ pts = bv.points(ctrl, n=200) # (200, 2) NumPy array, from ctrl[0] to ctrl[-1]
85
+ bv.animate(ctrl, verbose=True).save("curve.gif")
86
+ ```
87
+
88
+ <p align="center">
89
+ <img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/simple.gif" width="320" alt="A cubic Bézier curve being traced">
90
+ </p>
91
+
92
+ - **Input:** control points can be a list or a NumPy array of shape `(k, d)`, in any dimension `d`; the result has shape `(n, d)`.
93
+ - **Displaying:** `.show()` opens a window. In Jupyter, an animation that is the last expression in a cell plays inline.
94
+ - **Saving:** `.save()` writes `.gif` (Pillow) or `.mp4` (needs ffmpeg), and works on servers and in CI without a display.
95
+
96
+ ## Gallery
97
+
98
+ Ten short, self-contained scripts in [`examples/`](https://github.com/venkateshwara-gopisetti/Bezier-Curves/tree/master/examples), each a few dozen lines. Click an image for its code.
99
+
100
+ <table>
101
+ <tr><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/loop_animation.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/loop.gif" alt="A loop, every level drawn"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/loop_animation.py">A loop, every level drawn</a></sub></td><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/generative_art.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/generative_art.png" alt="3,000 curves in one call"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/generative_art.py">3,000 curves in one call</a></sub></td><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/calligraphy.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/calligraphy.png" alt="Broad-nib calligraphy"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/calligraphy.py">Broad-nib calligraphy</a></sub></td></tr>
102
+ <tr><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/easing.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/easing.png" alt="CSS easing curves"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/easing.py">CSS easing curves</a></sub></td><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/curvature_comb.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/curvature_comb.png" alt="Curvature comb"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/curvature_comb.py">Curvature comb</a></sub></td><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/helix_3d.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/helix_3d.png" alt="A 3-D spring"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/helix_3d.py">A 3-D spring</a></sub></td></tr>
103
+ <tr><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/heart.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/heart.png" alt="Two mirrored cubics"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/heart.py">Two mirrored cubics</a></sub></td><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/arc_length.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/arc_length.png" alt="Even spacing by length"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/arc_length.py">Even spacing by length</a></sub></td><td align="center" width="33%"><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/subdivision.py"><img src="https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/gallery/subdivision.png" alt="Recursive subdivision"></a><br><sub><a href="https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/examples/subdivision.py">Recursive subdivision</a></sub></td></tr>
104
+ </table>
105
+
106
+ ## API
107
+
108
+ | function | returns |
109
+ |---|---|
110
+ | `points(ctrl, n=100, t=None)` | `(n, d)` points at `n` evenly spaced `t` in [0, 1], or at the `t` values you pass |
111
+ | `points_batch(curves, n=100)` | `(m, n, d)` points for `m` curves of equal degree, given as `(m, k, d)` |
112
+ | `casteljau_steps(ctrl, t)` | every level of the construction: `[(k, d), (k-1, d), …, (1, d)]` |
113
+ | `split(ctrl, t=0.5)` | `(left, right)`: two curves of the same degree that join at `t` |
114
+ | `derivative(ctrl)` | control points of the derivative (hodograph) curve |
115
+ | `elevate(ctrl, times=1)` | the same curve with `times` more control points |
116
+ | `arc_length(ctrl)` | the curve's length (Gauss–Legendre quadrature, error around 1e-10) |
117
+ | `animate(ctrl, frames=100, verbose=False, …)` | a `BezierAnimation` with `.save()`, `.show()` and `.to_jshtml()` |
118
+ | `random_control_points(n, seed=None)` | `n` random integer points in [-100, 100) |
119
+ | `set_backend(name)` / `get_backend()` | choose or report the backend: `"numpy"`, `"numba"` or `"auto"` |
120
+
121
+ `animate()` also takes `labels`, `fps`, `hold` (frames to pause on the finished curve), `size` (pixels), `cmap` and `title`. Every function has a docstring with the details; try `help(bv.animate)`.
122
+
123
+ ```python
124
+ import numpy as np
125
+
126
+ left, right = bv.split(ctrl, 0.5)
127
+ velocity = bv.points(bv.derivative(ctrl), n=200) # tangent vectors along the curve
128
+ length = bv.arc_length(ctrl)
129
+ many = bv.points_batch(np.random.rand(10_000, 4, 2), n=100) # (10000, 100, 2)
130
+ ```
131
+
132
+ ## Command line
133
+
134
+ ```bash
135
+ beziervis --points "0,0 5,10 9,7 4,3" --verbose --save curve.gif
136
+ beziervis -n 5 --seed 42 # 5 random control points, reproducible
137
+ python -m beziervis --help # same thing, without the script on PATH
138
+ ```
139
+
140
+ | option | meaning |
141
+ |---|---|
142
+ | `-p, --points "x,y x,y …"` | control points (otherwise random) |
143
+ | `-n N` | number of random control points (default 4) |
144
+ | `--seed S` | random seed |
145
+ | `-v, --verbose` | draw the intermediate construction lines |
146
+ | `-f, --frames F` / `--fps R` | animation steps (default 100) and playback speed (default 30) |
147
+ | `--size PX` / `--no-labels` | figure size in pixels; hide point labels |
148
+ | `-s, --save FILE` | write `.gif` or `.mp4` instead of opening a window |
149
+
150
+ ## How de Casteljau's algorithm works
151
+
152
+ A Bézier curve is defined by its control points (`A0 … A3` below). To find the point at parameter `t`:
153
+
154
+ 1. Walk a fraction `t` along each edge of the control polygon. That gives one fewer point (`B0 … B2`).
155
+ 2. Repeat on the new points (`C0, C1`), then again, until a single point is left.
156
+ 3. That point (red) is on the curve. Sweep `t` from 0 to 1 and it traces the whole curve.
157
+
158
+ ![The same cubic curve at t = 0.2, 0.4, 0.6 and 0.8](https://raw.githubusercontent.com/venkateshwara-gopisetti/Bezier-Curves/master/docs/assets/how-it-works.png)
159
+
160
+ ```python
161
+ steps = bv.casteljau_steps(ctrl, t=0.4) # [A (4×2), B (3×2), C (2×2), point (1×2)]
162
+ ```
163
+
164
+ The construction also splits a curve in two exactly: `A0, B0, C0` and the red point are the control points of the left half. This is how `split()` is implemented.
165
+
166
+ ## Performance
167
+
168
+ Points are evaluated with a precomputed **Bernstein matrix** and one matrix multiply. Above degree 30, where that becomes numerically fragile, a **vectorised de Casteljau** is used instead. When Numba is installed, JIT-compiled kernels (multi-threaded for large inputs) are used automatically. Every backend agrees with the others to within 1e-12.
169
+
170
+ | case | naive Python | NumPy Bernstein | NumPy de Casteljau | Numba serial | Numba parallel |
171
+ |---|---|---|---|---|---|
172
+ | cubic, 1k points | 5.95 ms | 60 µs | 53.6 µs | 22.8 µs | 21.1 µs |
173
+ | cubic, 1M points | – | 71.5 ms | 79.2 ms | 25.9 ms | 10.6 ms |
174
+ | degree 10, 100k points | – | 21.4 ms | 52.4 ms | 7.93 ms | 2.33 ms |
175
+ | degree 50, 100k points | – | – | 1.02 s | 131 ms | 25 ms |
176
+ | 10k cubics × 100 points | – | 36.1 ms | – | – | 4.85 ms |
177
+
178
+ <sub>Best of 5 runs on Windows 11, Python 3.12, NumPy 2.5, Numba 0.68. To reproduce: `python benchmarks/bench.py`.</sub>
179
+
180
+ - **Choosing a backend:** set `BEZIERVIS_BACKEND=numpy|numba|auto` before import, or call `bv.set_backend(...)` at any time.
181
+ - **First Numba call:** it compiles the kernels, which takes about a second the first time and is then cached on disk.
182
+ - **Small inputs:** for a single curve with a few hundred points, every backend takes microseconds, so pick whichever you have installed.
183
+
184
+ ## FAQ
185
+
186
+ **Saving `.mp4` fails.** MP4 needs [ffmpeg](https://ffmpeg.org/download.html) on your `PATH`. GIF needs only Pillow.
187
+
188
+ **The animation is cluttered with many control points.** Use `verbose=False`, which draws only the polygon and the curve, or `labels=False`. Labels switch off automatically above 10 points.
189
+
190
+ **Can I animate 3-D curves?** Not yet; `animate()` draws 2-D curves. The maths functions (`points`, `split`, `derivative`, …) work in any dimension. 3-D animation is on the [roadmap](https://github.com/venkateshwara-gopisetti/Bezier-Curves/issues).
191
+
192
+ **How does this compare with the [`bezier`](https://pypi.org/project/bezier/) package?** `bezier` is a mature computational-geometry library with curve intersection, surfaces and a compiled core, and the right choice for CAD-grade geometry. beziervis is smaller and focused on teaching and visualising the construction, plus fast batch evaluation in pure NumPy or Numba.
193
+
194
+ ## Contributing
195
+
196
+ Bug reports, ideas and pull requests are welcome. See [CONTRIBUTING.md](https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/CONTRIBUTING.md) for setup, tests and style. Issues labelled [good first issue](https://github.com/venkateshwara-gopisetti/Bezier-Curves/labels/good%20first%20issue) are a good place to start.
197
+
198
+ ```bash
199
+ git clone https://github.com/venkateshwara-gopisetti/Bezier-Curves && cd Bezier-Curves
200
+ pip install -e ".[dev]" && pytest
201
+ ```
202
+
203
+ ## Citation
204
+
205
+ If beziervis helps your research or teaching, please cite it. GitHub's "Cite this repository" button (from [`CITATION.cff`](https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/CITATION.cff)) gives BibTeX and APA.
206
+
207
+ ## License
208
+
209
+ [MIT](https://github.com/venkateshwara-gopisetti/Bezier-Curves/blob/master/LICENSE) © Venkateshwara Gopisetti
@@ -0,0 +1,12 @@
1
+ beziervis/__init__.py,sha256=4D9YJTt-g5eZJ5UdedQ-F5YqztrOQ3F4d4zfFv0yLa8,1687
2
+ beziervis/__main__.py,sha256=vReXeT9PKcw3yghOqF_VuYRZaHpC9iJgCMyu89dxWsA,90
3
+ beziervis/_numba.py,sha256=vrXuvNen7bZAfmb97gNSaOfutwwrg3NmxR8A6-9hNPM,2339
4
+ beziervis/animation.py,sha256=w_ZpuE3kN_dx2CPg9GsxB2_w4r9VUI2C-Pa3v9WFng0,9744
5
+ beziervis/cli.py,sha256=YfwpOxPxBQ976uoqHaZVelhyK65GnAylxIIxgkxTVv4,3623
6
+ beziervis/core.py,sha256=c7UHj0OuVrLFv1i0_OojCackkk1vDKfVDyZ3YEQpbPY,9151
7
+ beziervis/ops.py,sha256=RbhLtW5FLUBoqg0kyR02Rl1DEefUNSJCXL0fQxajOvk,2829
8
+ beziervis-1.0.0.dist-info/METADATA,sha256=hXOK84Ruczz5qZ5WXWnq9IMx-LKDVl1tgFwz4W3FMcA,15462
9
+ beziervis-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ beziervis-1.0.0.dist-info/entry_points.txt,sha256=BFsBTErw9aAWlx91wCE3yBifyd_H0s6S78ZNfvtLgo8,49
11
+ beziervis-1.0.0.dist-info/licenses/LICENSE,sha256=d1vVTW6kWJRiCWFFdXkai32a299-R8GdHvhuVaxt5ZA,1085
12
+ beziervis-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ beziervis = beziervis.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 Venkateshwara Gopisetti
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.