ezmsg-kinematics 0.1__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.
@@ -0,0 +1,2 @@
1
+ from . import min_jerk as min_jerk
2
+ from .__version__ import __version__ as __version__
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1'
22
+ __version_tuple__ = version_tuple = (0, 1)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,367 @@
1
+ """Minimum-jerk reach generator with continuous re-planning.
2
+
3
+ Stdlib-only, scalar in / scalar out, dataclass-backed state. Deliberately free
4
+ of any framework dependency so the same generator can run inside a streaming
5
+ graph, inside a task's render loop, or in an offline analysis, and produce the
6
+ same numbers in all three.
7
+
8
+ The classic minimum-jerk reach is a function of time: over a duration ``T``,
9
+ position follows ``p(t) = A + s(τ)·(B - A)`` with ``τ = t/T`` and
10
+ ``s(τ) = 10τ³ - 15τ⁴ + 6τ⁵``, giving the familiar symmetric bell-shaped speed
11
+ profile. That is the whole story when the generator is what moves the effector.
12
+ It is not, when something else is also pushing -- a decoder, a participant, a
13
+ disturbance -- because the effector then ends up somewhere the plan never
14
+ predicted, and a plan that only knows about elapsed time has nothing to say
15
+ about it.
16
+
17
+ This generator runs a reach in two phases.
18
+
19
+ **Ballistic.** For ``ballistic_duration`` after the reach starts, the command is
20
+ pure feedforward: the planned min-jerk velocity at the elapsed time, along the
21
+ original start→target axis, regardless of where the effector actually is. Real
22
+ reaches begin open-loop, and it means the launch command is decisive and
23
+ identical every time -- valuable if something downstream has to learn it.
24
+
25
+ **Re-planning.** After that, every step re-solves the minimum-jerk problem from
26
+ where the effector *is* to the target, and emits the beginning of that fresh
27
+ solution. The boundary conditions are the measured position, the current
28
+ commanded velocity and acceleration, and rest at the target.
29
+
30
+ Re-planning is what makes the response to a disturbance fall out rather than
31
+ have to be designed:
32
+
33
+ * **Undisturbed, it changes nothing.** The tail of a minimum-jerk trajectory is
34
+ itself the minimum-jerk solution for the remaining problem, so re-planning
35
+ from a point on your own trajectory reproduces it exactly. An effector that
36
+ was never pushed follows the original reach, including its deceleration onto
37
+ the target.
38
+ * **Disturbed, it compensates partially, and by the right amount.** A fresh plan
39
+ cannot contain a velocity discontinuity, so it curves back toward the target
40
+ rather than snapping to the new bearing. How hard it corrects is set by how
41
+ much time is left, not by a blend weight anyone has to tune.
42
+ * **Speed and turning trade off on their own.** A large heading error forces the
43
+ new polynomial to spend its early effort turning, which suppresses forward
44
+ speed for as long as the turn takes.
45
+ * **It always eases in.** Rest at the target is a boundary condition of every
46
+ re-plan, so there is no approach speed to tune and no overshoot to damp.
47
+
48
+ The remaining horizon is floored at ``min_horizon``. Without a floor, an
49
+ effector held away from the target as its deadline runs out demands unbounded
50
+ speed -- the time-to-go singularity. The floor costs exactness only in the final
51
+ ``min_horizon`` of an undisturbed reach, where everything involved is already
52
+ near zero. ``max_speed_ratio`` clamps the command as a second line of defence.
53
+
54
+ Time is passed in rather than read from a clock, so a caller can drive this from
55
+ whatever timebase its data carries -- a stream's sample timestamps, a shared
56
+ network clock, or a recording being replayed offline. Two processes given the
57
+ same reach epoch and the same timestamps produce the same commands.
58
+
59
+ Typical use::
60
+
61
+ reach = MinJerkReach()
62
+ begin_reach(reach, cue_time, *effector_xy, *target_xy, peak_speed=800.0)
63
+ while reaching:
64
+ vx, vy = step(reach, now, *effector_xy, movement_allowed=True)
65
+ """
66
+
67
+ from __future__ import annotations
68
+
69
+ import math
70
+ from dataclasses import dataclass
71
+ from enum import Enum
72
+
73
+ __all__ = ["MinJerkReach", "ReplanSeed", "begin_reach", "reset", "step"]
74
+
75
+
76
+ class ReplanSeed(str, Enum):
77
+ """Which velocity a re-plan treats as the effector's current velocity.
78
+
79
+ This is a modelling choice, not a tuning knob, and it matters whenever
80
+ something other than this generator is moving the effector.
81
+
82
+ ``COMMANDED`` continues from the velocity this generator last asked for. The
83
+ plan stays continuous with its own intent and treats the effector's position
84
+ as feedback about where that intent ended up. Appropriate when the output
85
+ represents what someone or something *wants* -- a disturbance moved the
86
+ effector, but it did not move the intent. This is the default.
87
+
88
+ ``MEASURED`` continues from the effector's observed velocity, differentiated
89
+ from successive positions. The plan stays continuous with what is physically
90
+ happening. Appropriate when the output drives the effector directly and you
91
+ want the generator to own the real dynamics. Noisier, and if the output is
92
+ being used as a training label it will carry whatever error the disturbance
93
+ injected.
94
+ """
95
+
96
+ COMMANDED = "commanded"
97
+ MEASURED = "measured"
98
+
99
+
100
+ @dataclass
101
+ class MinJerkReach:
102
+ """State for one minimum-jerk reach.
103
+
104
+ Lifecycle:
105
+ * :func:`begin_reach` starts (or restarts) a reach. Call it whenever
106
+ movement becomes allowed and whenever the target moves mid-reach.
107
+ * :func:`step` returns a velocity for the current time and effector
108
+ position. While movement is gated off, pass ``movement_allowed=False``
109
+ -- the command goes to zero and the reach waits.
110
+ * :func:`reset` is optional; it marks the reach inactive so a later
111
+ :func:`step` returns zero even with ``movement_allowed=True``.
112
+
113
+ Fields:
114
+ t0: timestamp the reach started, in the caller's timebase.
115
+ start_x, start_y: effector position captured at ``begin_reach``.
116
+ target_x, target_y: target captured at ``begin_reach``.
117
+ D: straight-line distance from start to target.
118
+ T: nominal reach duration. Chosen so peak speed equals ``peak_speed``.
119
+ ballistic_duration: how long the feedforward phase lasts.
120
+ min_horizon: floor on the remaining time a re-plan is given.
121
+ max_speed: absolute clamp on commanded speed. 0 disables.
122
+ seed: which velocity a re-plan continues from.
123
+ cmd_vx, cmd_vy: velocity last commanded -- the plan's own motor state.
124
+ cmd_ax, cmd_ay: acceleration last commanded.
125
+ last_x, last_y: effector position at the previous step, for the
126
+ ``MEASURED`` seed.
127
+ t_prev: timestamp of the previous step.
128
+ active: False before ``begin_reach`` or after ``reset``.
129
+ """
130
+
131
+ t0: float = 0.0
132
+ start_x: float = 0.0
133
+ start_y: float = 0.0
134
+ target_x: float = 0.0
135
+ target_y: float = 0.0
136
+ D: float = 0.0
137
+ T: float = 0.0
138
+ ballistic_duration: float = 0.5
139
+ min_horizon: float = 0.3
140
+ max_speed: float = 0.0
141
+ seed: ReplanSeed = ReplanSeed.COMMANDED
142
+ cmd_vx: float = 0.0
143
+ cmd_vy: float = 0.0
144
+ cmd_ax: float = 0.0
145
+ cmd_ay: float = 0.0
146
+ last_x: float = 0.0
147
+ last_y: float = 0.0
148
+ t_prev: float = 0.0
149
+ active: bool = False
150
+
151
+
152
+ def begin_reach(
153
+ state: MinJerkReach,
154
+ t0: float,
155
+ start_x: float,
156
+ start_y: float,
157
+ target_x: float,
158
+ target_y: float,
159
+ peak_speed: float,
160
+ *,
161
+ ballistic_duration: float = 0.5,
162
+ min_horizon: float = 0.3,
163
+ max_speed_ratio: float = 2.0,
164
+ seed: ReplanSeed = ReplanSeed.COMMANDED,
165
+ ) -> None:
166
+ """(Re)initialize ``state`` for a reach from a start point to a target.
167
+
168
+ ``t0`` is when the reach begins, in whatever timebase the caller passes to
169
+ :func:`step`. Anchoring to a timestamp the caller already has -- a cue
170
+ event's own arrival time, say -- rather than to a clock read here is what
171
+ lets two processes agree without exchanging state.
172
+
173
+ ``peak_speed`` is the peak of the planned velocity bell, in the caller's
174
+ distance unit per second. The duration is derived from it and the distance,
175
+ so a longer reach takes proportionally longer rather than going faster.
176
+
177
+ ``ballistic_duration`` is how long the command ignores the effector's
178
+ position. 0 re-plans from the first step, which is well defined but gives up
179
+ the identical, decisive launch. Values at or beyond the reach's own duration
180
+ make it purely feedforward.
181
+
182
+ ``min_horizon`` floors the time a re-plan is allowed to assume remains.
183
+ ``max_speed_ratio`` clamps commanded speed to that multiple of
184
+ ``peak_speed``; 0 disables the clamp. Both guard the same failure -- an
185
+ effector held away from the target while its deadline expires.
186
+
187
+ A degenerate reach -- zero distance, or a non-positive ``peak_speed`` --
188
+ leaves the state inactive rather than raising, so a caller driving this from
189
+ live events need not pre-filter a target that coincides with the effector.
190
+ """
191
+ state.t0 = float(t0)
192
+ state.t_prev = float(t0)
193
+ state.start_x = float(start_x)
194
+ state.start_y = float(start_y)
195
+ state.target_x = float(target_x)
196
+ state.target_y = float(target_y)
197
+ state.last_x = state.start_x
198
+ state.last_y = state.start_y
199
+
200
+ dx = state.target_x - state.start_x
201
+ dy = state.target_y - state.start_y
202
+ state.D = math.hypot(dx, dy)
203
+
204
+ # The velocity bell peaks at 1.875 * D / T, so this choice of T makes
205
+ # peak_speed the peak.
206
+ if peak_speed > 0.0 and state.D > 0.0:
207
+ state.T = 1.875 * state.D / float(peak_speed)
208
+ else:
209
+ state.T = 0.0
210
+
211
+ state.ballistic_duration = max(0.0, float(ballistic_duration))
212
+ state.min_horizon = max(1e-6, float(min_horizon))
213
+ state.max_speed = max(0.0, float(max_speed_ratio)) * float(peak_speed)
214
+ state.seed = seed
215
+
216
+ # A reach starts from rest. Re-planning later continues from whatever the
217
+ # ballistic phase handed over, but the plan's motor state begins at zero.
218
+ state.cmd_vx = 0.0
219
+ state.cmd_vy = 0.0
220
+ state.cmd_ax = 0.0
221
+ state.cmd_ay = 0.0
222
+
223
+ state.active = state.D > 0.0 and state.T > 0.0
224
+
225
+
226
+ def reset(state: MinJerkReach) -> None:
227
+ """Mark the reach inactive; subsequent :func:`step` calls return zero."""
228
+ state.active = False
229
+
230
+
231
+ def _quintic_to_rest(p0: float, v0: float, a0: float, pf: float, T: float) -> tuple[float, float, float]:
232
+ """Cubic..quintic coefficients taking ``(p0, v0, a0)`` to ``(pf, 0, 0)`` in ``T``.
233
+
234
+ The minimum-jerk solution for fixed position/velocity/acceleration at both
235
+ ends is the unique quintic satisfying them. With ``v0 = a0 = 0`` this
236
+ reduces to the familiar ``10τ³ - 15τ⁴ + 6τ⁵``.
237
+ """
238
+ T2 = T * T
239
+ T3 = T2 * T
240
+ T4 = T2 * T2
241
+ T5 = T4 * T
242
+
243
+ # Residuals: what the already-determined terms fail to deliver at t = T.
244
+ P = pf - p0 - v0 * T - 0.5 * a0 * T2
245
+ V = -v0 - a0 * T
246
+ A = -a0
247
+
248
+ c3 = (10.0 * P - 4.0 * V * T + 0.5 * A * T2) / T3
249
+ c4 = (-15.0 * P + 7.0 * V * T - A * T2) / T4
250
+ c5 = (6.0 * P - 3.0 * V * T + 0.5 * A * T2) / T5
251
+ return c3, c4, c5
252
+
253
+
254
+ def _eval_quintic(v0: float, a0: float, c3: float, c4: float, c5: float, t: float) -> tuple[float, float]:
255
+ """Velocity and acceleration of the plan at time ``t`` from its start."""
256
+ t2 = t * t
257
+ t3 = t2 * t
258
+ t4 = t2 * t2
259
+ v = v0 + a0 * t + 3.0 * c3 * t2 + 4.0 * c4 * t3 + 5.0 * c5 * t4
260
+ a = a0 + 6.0 * c3 * t + 12.0 * c4 * t2 + 20.0 * c5 * t3
261
+ return v, a
262
+
263
+
264
+ def _ballistic_command(state: MinJerkReach, elapsed: float) -> tuple[float, float, float, float]:
265
+ """Planned velocity and acceleration at ``elapsed``, along the original axis."""
266
+ tau = elapsed / state.T
267
+ if tau < 0.0:
268
+ tau = 0.0
269
+ elif tau > 1.0:
270
+ tau = 1.0
271
+
272
+ # s'(τ) = 30τ²(1-τ)², s''(τ) = 60τ - 180τ² + 120τ³
273
+ one_minus = 1.0 - tau
274
+ ds = 30.0 * tau * tau * one_minus * one_minus
275
+ dds = 60.0 * tau - 180.0 * tau * tau + 120.0 * tau * tau * tau
276
+
277
+ ux = (state.target_x - state.start_x) / state.D
278
+ uy = (state.target_y - state.start_y) / state.D
279
+ speed = state.D * ds / state.T
280
+ accel = state.D * dds / (state.T * state.T)
281
+ return speed * ux, speed * uy, accel * ux, accel * uy
282
+
283
+
284
+ def step(
285
+ state: MinJerkReach,
286
+ t: float,
287
+ pos_x: float,
288
+ pos_y: float,
289
+ movement_allowed: bool,
290
+ ) -> tuple[float, float]:
291
+ """Velocity ``(vx, vy)`` for an effector at ``(pos_x, pos_y)`` at time ``t``.
292
+
293
+ ``t`` is in the same timebase as the ``t0`` given to :func:`begin_reach`.
294
+
295
+ Returns ``(0.0, 0.0)`` when movement is not allowed or no reach is active.
296
+ While movement is disallowed the command is held at rest and the clock
297
+ reference is carried forward, so resuming does not produce a step
298
+ proportional to how long the pause lasted.
299
+ """
300
+ if not movement_allowed or not state.active or state.T <= 0.0:
301
+ if state.active:
302
+ # Commanded rest, not merely "no output": whatever the effector does
303
+ # while gated off, the plan is not asking for it.
304
+ state.cmd_vx = state.cmd_vy = 0.0
305
+ state.cmd_ax = state.cmd_ay = 0.0
306
+ state.t_prev = float(t)
307
+ state.last_x = float(pos_x)
308
+ state.last_y = float(pos_y)
309
+ return 0.0, 0.0
310
+
311
+ elapsed = float(t) - state.t0
312
+ if elapsed < 0.0:
313
+ # A timestamp before the reach began; nothing has started yet.
314
+ return 0.0, 0.0
315
+
316
+ if elapsed < state.ballistic_duration:
317
+ vx, vy, ax, ay = _ballistic_command(state, elapsed)
318
+ state.cmd_vx, state.cmd_vy = vx, vy
319
+ state.cmd_ax, state.cmd_ay = ax, ay
320
+ state.t_prev = float(t)
321
+ state.last_x, state.last_y = float(pos_x), float(pos_y)
322
+ return vx, vy
323
+
324
+ dt = float(t) - state.t_prev
325
+ if dt <= 0.0:
326
+ # Repeated or out-of-order timestamp: re-planning over a zero interval
327
+ # is undefined, and the previous command is still the best answer.
328
+ return state.cmd_vx, state.cmd_vy
329
+
330
+ if state.seed is ReplanSeed.MEASURED:
331
+ seed_vx = (float(pos_x) - state.last_x) / dt
332
+ seed_vy = (float(pos_y) - state.last_y) / dt
333
+ else:
334
+ seed_vx, seed_vy = state.cmd_vx, state.cmd_vy
335
+
336
+ # Floored so a stalled effector cannot demand unbounded speed as its
337
+ # deadline expires.
338
+ horizon = state.T - elapsed
339
+ if horizon < state.min_horizon:
340
+ horizon = state.min_horizon
341
+
342
+ # Solved per axis: with rest at both ends this is the straight-line reach,
343
+ # and with a nonzero starting velocity it curves, which is exactly the
344
+ # partial compensation a disturbance should get.
345
+ cx3, cx4, cx5 = _quintic_to_rest(float(pos_x), seed_vx, state.cmd_ax, state.target_x, horizon)
346
+ cy3, cy4, cy5 = _quintic_to_rest(float(pos_y), seed_vy, state.cmd_ay, state.target_y, horizon)
347
+
348
+ # Advance one control step along the fresh plan. Evaluating at 0 would just
349
+ # return the seed velocity, which is why re-planning has to step forward.
350
+ ahead = dt if dt < horizon else horizon
351
+ vx, ax = _eval_quintic(seed_vx, state.cmd_ax, cx3, cx4, cx5, ahead)
352
+ vy, ay = _eval_quintic(seed_vy, state.cmd_ay, cy3, cy4, cy5, ahead)
353
+
354
+ if state.max_speed > 0.0:
355
+ speed = math.hypot(vx, vy)
356
+ if speed > state.max_speed:
357
+ scale = state.max_speed / speed
358
+ vx *= scale
359
+ vy *= scale
360
+ ax *= scale
361
+ ay *= scale
362
+
363
+ state.cmd_vx, state.cmd_vy = vx, vy
364
+ state.cmd_ax, state.cmd_ay = ax, ay
365
+ state.t_prev = float(t)
366
+ state.last_x, state.last_y = float(pos_x), float(pos_y)
367
+ return vx, vy
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: ezmsg-kinematics
3
+ Version: 0.1
4
+ Summary: ezmsg units and utility code for streaming kinematics
5
+ Author-email: Chadwick Boulay <chad@cbneurotech.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: ezmsg>=3.9.0
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ezmsg-kinematics
13
+
14
+ Short description of your ezmsg package.
15
+
16
+ ## Overview
17
+
18
+ `ezmsg-kinematics` provides ... for the `ezmsg <https://www.ezmsg.org>`_ framework.
19
+
20
+ Key features:
21
+
22
+ * **Feature 1** - Description
23
+ * **Feature 2** - Description
24
+ * **Feature 3** - Description
25
+
26
+ ## Installation
27
+
28
+ Install from PyPI:
29
+
30
+ ```bash
31
+ pip install ezmsg-kinematics
32
+ ```
33
+
34
+ Or install the latest development version:
35
+
36
+ ```bash
37
+ pip install git+https://github.com/ezmsg-org/ezmsg-kinematics@main
38
+ ```
39
+
40
+ ## Dependencies
41
+
42
+ - `ezmsg`
43
+
44
+ ## Usage
45
+
46
+ See the `examples` folder for usage examples.
47
+
48
+ ```python
49
+ import ezmsg.core as ez
50
+ from ezmsg.kinematics import MyUnit
51
+
52
+ # Your usage example here
53
+ ```
54
+
55
+ For general ezmsg tutorials and guides, visit [ezmsg.org](https://www.ezmsg.org).
56
+
57
+ ## Development
58
+
59
+ We use [`uv`](https://docs.astral.sh/uv/getting-started/installation/) for development.
60
+
61
+ 1. Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/) if not already installed.
62
+ 2. Fork this repository and clone your fork locally.
63
+ 3. Open a terminal and `cd` to the cloned folder.
64
+ 4. Run `uv sync` to create a `.venv` and install dependencies.
65
+ 5. (Optional) Install pre-commit hooks: `uv run pre-commit install`
66
+ 6. After making changes, run the test suite: `uv run pytest tests`
67
+
68
+ ## License
69
+
70
+ MIT License - see [LICENSE](LICENSE) for details.
@@ -0,0 +1,7 @@
1
+ ezmsg/kinematics/__init__.py,sha256=HkBWAicAb_NcDZOJSNUkdASQf-2PejpscX7HrqUmCZs,87
2
+ ezmsg/kinematics/__version__.py,sha256=k5I4VfQVfm1yo61MMeUeE-6DgL-lwsONMdtjk5JZBM0,515
3
+ ezmsg/kinematics/min_jerk.py,sha256=kxSAOtmsDsHM8_s5lvtBKQe_sNYurd7uvxHjUN8bxP8,15231
4
+ ezmsg_kinematics-0.1.dist-info/METADATA,sha256=e9oX3XAscRdEyjL86Y0yZSUQAC-6gVYxv9bW3-_13YA,1622
5
+ ezmsg_kinematics-0.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
6
+ ezmsg_kinematics-0.1.dist-info/licenses/LICENSE,sha256=BDD8rfac1Ur7mp0_3izEdr6fHgSA3Or6U1Kb0ZAWsow,1066
7
+ ezmsg_kinematics-0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ezmsg-org
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.