|
| 1 | +from collections.abc import Callable # noqa: EXE002 |
| 2 | + |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import numpy as np |
| 5 | + |
| 6 | + |
| 7 | +class ParabolicBlendTrajectory: |
| 8 | + """ |
| 9 | + Class to generate trajectories composed of linear segments with parabolic blends at via points. |
| 10 | +
|
| 11 | + The trajectory duration is extended: |
| 12 | + total_duration = t[-1] - t[0] + (dt_blend[0] + dt_blend[-1]) / 2 |
| 13 | +
|
| 14 | + Initial and final velocities are set to zero (q̇0,1 = q̇N,N+1 = 0). |
| 15 | +
|
| 16 | + Parameters |
| 17 | + ---------- |
| 18 | + q : list | np.ndarray |
| 19 | + Positions of via points (length N). |
| 20 | + t : list | np.ndarray |
| 21 | + Nominal times at which via points are reached (length N). |
| 22 | + dt_blend : list | np.ndarray |
| 23 | + Blend durations at via points (length N). |
| 24 | + dt : float, optional |
| 25 | + Sampling interval for plotting trajectory. Default is 0.01. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + q: list | np.ndarray, |
| 31 | + t: list | np.ndarray, |
| 32 | + dt_blend: list | np.ndarray, |
| 33 | + dt: float = 0.01, |
| 34 | + ) -> None: |
| 35 | + self.q = np.asarray(q, dtype=float) |
| 36 | + self.t = np.asarray(t, dtype=float) |
| 37 | + self.dt_blend = np.asarray(dt_blend, dtype=float) |
| 38 | + self.dt = dt |
| 39 | + |
| 40 | + if not (len(self.q) == len(self.t) == len(self.dt_blend)): |
| 41 | + raise ValueError("Lengths of q, t, and dt_blend must match.") |
| 42 | + |
| 43 | + def generate(self) -> tuple[Callable[[float], tuple[float, float, float]], float]: |
| 44 | + """ |
| 45 | + Generate the parabolic blend trajectory function. |
| 46 | +
|
| 47 | + Returns |
| 48 | + ------- |
| 49 | + trajectory_function : callable |
| 50 | + Function that takes a time value and returns position, velocity, and acceleration. |
| 51 | + total_duration : float |
| 52 | + The total duration of the trajectory. |
| 53 | + """ |
| 54 | + # Use lowercase for count variable per style |
| 55 | + n = len(self.q) |
| 56 | + |
| 57 | + # Vectorized computation of segment velocities with zero initial and final |
| 58 | + v_before = np.zeros(n) |
| 59 | + # Calculate differences in positions and times |
| 60 | + dq = np.diff(self.q) |
| 61 | + dt = np.diff(self.t) |
| 62 | + # Vectorized velocity calculation |
| 63 | + v_before[1:] = dq / dt |
| 64 | + |
| 65 | + # Shift velocities for v_after |
| 66 | + v_after = np.zeros(n) |
| 67 | + v_after[:-1] = v_before[1:] |
| 68 | + |
| 69 | + # Accelerations for parabolic blends |
| 70 | + a = (v_after - v_before) / self.dt_blend |
| 71 | + |
| 72 | + # Preallocate arrays for region data with structure of arrays (SoA) |
| 73 | + # Estimating 2*n-1 regions (initial blend + n-1 pairs of linear+blend) |
| 74 | + num_regions = 2 * n - 1 |
| 75 | + reg_t0 = np.zeros(num_regions) |
| 76 | + reg_t1 = np.zeros(num_regions) |
| 77 | + reg_q0 = np.zeros(num_regions) |
| 78 | + reg_v0 = np.zeros(num_regions) |
| 79 | + reg_a = np.zeros(num_regions) |
| 80 | + |
| 81 | + # Initial blend |
| 82 | + reg_idx = 0 |
| 83 | + t0 = self.t[0] - self.dt_blend[0] / 2 |
| 84 | + t1 = self.t[0] + self.dt_blend[0] / 2 |
| 85 | + reg_t0[reg_idx] = t0 |
| 86 | + reg_t1[reg_idx] = t1 |
| 87 | + reg_q0[reg_idx] = self.q[0] |
| 88 | + reg_v0[reg_idx] = v_before[0] |
| 89 | + reg_a[reg_idx] = a[0] |
| 90 | + reg_idx += 1 |
| 91 | + |
| 92 | + # Build remaining regions efficiently |
| 93 | + for k in range(n - 1): |
| 94 | + # Constant-velocity segment |
| 95 | + t0_c = reg_t1[reg_idx - 1] |
| 96 | + t1_c = self.t[k + 1] - self.dt_blend[k + 1] / 2 |
| 97 | + |
| 98 | + # Calculate position at start of constant velocity segment |
| 99 | + dt0 = t0_c - reg_t0[reg_idx - 1] |
| 100 | + q0_c = ( |
| 101 | + reg_q0[reg_idx - 1] + reg_v0[reg_idx - 1] * dt0 + 0.5 * reg_a[reg_idx - 1] * dt0**2 |
| 102 | + ) |
| 103 | + |
| 104 | + # Store constant velocity segment |
| 105 | + reg_t0[reg_idx] = t0_c |
| 106 | + reg_t1[reg_idx] = t1_c |
| 107 | + reg_q0[reg_idx] = q0_c |
| 108 | + reg_v0[reg_idx] = v_after[k] |
| 109 | + reg_a[reg_idx] = 0.0 |
| 110 | + reg_idx += 1 |
| 111 | + |
| 112 | + # Parabolic blend |
| 113 | + t0_b = t1_c |
| 114 | + t1_b = self.t[k + 1] + self.dt_blend[k + 1] / 2 |
| 115 | + |
| 116 | + # Calculate position at start of blend |
| 117 | + dt0b = t0_b - reg_t0[reg_idx - 1] |
| 118 | + q0_b = reg_q0[reg_idx - 1] + reg_v0[reg_idx - 1] * dt0b |
| 119 | + |
| 120 | + # Store parabolic blend |
| 121 | + reg_t0[reg_idx] = t0_b |
| 122 | + reg_t1[reg_idx] = t1_b |
| 123 | + reg_q0[reg_idx] = q0_b |
| 124 | + reg_v0[reg_idx] = v_before[k + 1] |
| 125 | + reg_a[reg_idx] = a[k + 1] |
| 126 | + reg_idx += 1 |
| 127 | + |
| 128 | + # Trim unused regions if we overestimated |
| 129 | + if reg_idx < num_regions: |
| 130 | + reg_t0 = reg_t0[:reg_idx] |
| 131 | + reg_t1 = reg_t1[:reg_idx] |
| 132 | + reg_q0 = reg_q0[:reg_idx] |
| 133 | + reg_v0 = reg_v0[:reg_idx] |
| 134 | + reg_a = reg_a[:reg_idx] |
| 135 | + |
| 136 | + # Determine overall duration |
| 137 | + t_start = reg_t0[0] |
| 138 | + t_end = reg_t1[-1] |
| 139 | + total_duration = t_end - t_start |
| 140 | + |
| 141 | + # Prepare binary search for region lookup |
| 142 | + region_boundaries = np.append(reg_t0[0], reg_t1) |
| 143 | + |
| 144 | + # Function to evaluate trajectory at any time t |
| 145 | + def trajectory_function(t: float) -> tuple[float, float, float]: |
| 146 | + """ |
| 147 | + Evaluate the trajectory at time t. |
| 148 | +
|
| 149 | + Parameters |
| 150 | + ---------- |
| 151 | + t : float |
| 152 | + Time at which to evaluate the trajectory |
| 153 | +
|
| 154 | + Returns |
| 155 | + ------- |
| 156 | + tuple[float, float, float] |
| 157 | + Tuple containing position, velocity, and acceleration at time t |
| 158 | + """ |
| 159 | + # Clip time to valid range |
| 160 | + t = np.clip(t, 0.0, total_duration) |
| 161 | + |
| 162 | + # Convert to absolute time |
| 163 | + t_abs = t + t_start |
| 164 | + |
| 165 | + # Find region using binary search |
| 166 | + region_idx = np.searchsorted(region_boundaries, t_abs, side="right") - 1 |
| 167 | + region_idx = min(region_idx, len(reg_t0) - 1) |
| 168 | + |
| 169 | + # Calculate values |
| 170 | + u = t_abs - reg_t0[region_idx] |
| 171 | + pos = reg_q0[region_idx] + reg_v0[region_idx] * u + 0.5 * reg_a[region_idx] * u**2 |
| 172 | + vel = reg_v0[region_idx] + reg_a[region_idx] * u |
| 173 | + acc = reg_a[region_idx] |
| 174 | + |
| 175 | + return pos, vel, acc |
| 176 | + |
| 177 | + return trajectory_function, total_duration |
| 178 | + |
| 179 | + def plot( |
| 180 | + self, |
| 181 | + times: np.ndarray | None = None, |
| 182 | + pos: np.ndarray | None = None, |
| 183 | + vel: np.ndarray | None = None, |
| 184 | + acc: np.ndarray | None = None, |
| 185 | + ) -> None: |
| 186 | + """ |
| 187 | + Plot the trajectory's position, velocity, and acceleration. |
| 188 | +
|
| 189 | + If trajectory data is not provided, it will be generated. |
| 190 | +
|
| 191 | + Parameters |
| 192 | + ---------- |
| 193 | + times : ndarray, optional |
| 194 | + Time samples; if None, generated from trajectory function. |
| 195 | + pos : ndarray, optional |
| 196 | + Position samples; if None, generated from trajectory function. |
| 197 | + vel : ndarray, optional |
| 198 | + Velocity samples; if None, generated from trajectory function. |
| 199 | + acc : ndarray, optional |
| 200 | + Acceleration samples; if None, generated from trajectory function. |
| 201 | + """ |
| 202 | + if times is None or pos is None or vel is None or acc is None: |
| 203 | + traj_func, total_duration = self.generate() |
| 204 | + times = np.arange(0.0, total_duration + self.dt, self.dt) |
| 205 | + pos = np.zeros_like(times) |
| 206 | + vel = np.zeros_like(times) |
| 207 | + acc = np.zeros_like(times) |
| 208 | + |
| 209 | + for i, t in enumerate(times): |
| 210 | + pos[i], vel[i], acc[i] = traj_func(t) |
| 211 | + |
| 212 | + fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True) |
| 213 | + ax1.plot(times, pos) |
| 214 | + ax1.set_ylabel("Position") |
| 215 | + ax2.plot(times, vel) |
| 216 | + ax2.set_ylabel("Velocity") |
| 217 | + ax3.plot(times, acc) |
| 218 | + ax3.set_ylabel("Acceleration") |
| 219 | + ax3.set_xlabel("Time") |
| 220 | + fig.tight_layout() |
| 221 | + plt.show() |
0 commit comments