1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
use tracing::debug;

use crate::{
    error::Error,
    traits::{JointTrajectoryClient, TrajectoryPoint},
    waits::WaitFuture,
};

/// JointVelocityLimiter limits the duration to make all joints velocities lower than the given
/// velocities limits at each TrajectoryPoint.
///
/// It does not change TrajectoryPoint velocities.
/// The duration for a TrajectoryPoint\[i\] is set to
/// ```Text
/// duration[i] = max(limited_duration_i[j=0], ...,  limited_duration_i[j=J-1], input_duration[i])
/// where
///  j : joint_index (0 <= j < J),
///  limited_duration_i[j] =
///   abs(TrajectoryPoint[i].positions[j]  - TrajectoryPoint[i-1].positions[j]) / velocity_limits[j]
/// ```
#[derive(Debug)]
pub struct JointVelocityLimiter<C>
where
    C: JointTrajectoryClient,
{
    client: C,
    velocity_limits: Vec<f64>,
}

impl<C> JointVelocityLimiter<C>
where
    C: JointTrajectoryClient,
{
    /// Creates a new `JointVelocityLimiter` with the given velocity limits.
    ///
    /// # Panics
    ///
    /// Panics if the lengths of `velocity_limits` and joints that `client` handles are different.
    #[track_caller]
    pub fn new(client: C, velocity_limits: Vec<f64>) -> Self {
        assert!(client.joint_names().len() == velocity_limits.len());
        Self {
            client,
            velocity_limits,
        }
    }

    /// Creates a new `JointVelocityLimiter` with the velocity limits defined in URDF.
    pub fn from_urdf(client: C, joints: &[urdf_rs::Joint]) -> Result<Self, Error> {
        let mut velocity_limits = Vec::new();
        for joint_name in client.joint_names() {
            if let Some(i) = joints.iter().position(|j| j.name == *joint_name) {
                let limit = joints[i].limit.velocity;
                velocity_limits.push(limit);
            } else {
                return Err(Error::NoJoint(joint_name));
            }
        }

        Ok(Self {
            client,
            velocity_limits,
        })
    }
}

impl<C> JointTrajectoryClient for JointVelocityLimiter<C>
where
    C: JointTrajectoryClient,
{
    fn joint_names(&self) -> Vec<String> {
        self.client.joint_names()
    }

    fn current_joint_positions(&self) -> Result<Vec<f64>, Error> {
        self.client.current_joint_positions()
    }

    fn send_joint_positions(
        &self,
        positions: Vec<f64>,
        duration: std::time::Duration,
    ) -> Result<WaitFuture, Error> {
        self.send_joint_trajectory(vec![TrajectoryPoint {
            positions,
            velocities: None,
            time_from_start: duration,
        }])
    }

    fn send_joint_trajectory(&self, trajectory: Vec<TrajectoryPoint>) -> Result<WaitFuture, Error> {
        let mut prev_positions = self.current_joint_positions()?;

        let mut limited_trajectory = vec![];
        let mut limited_duration_from_start = std::time::Duration::from_secs(0);
        let mut original_duration_from_start = std::time::Duration::from_secs(0);
        for (sequence_index, original_trajectory_point) in trajectory.iter().enumerate() {
            let mut limited_duration_from_prev = std::time::Duration::from_secs(0);
            let mut dominant_joint_index = 0;
            for (joint_index, prev_position) in prev_positions.iter().enumerate() {
                let single_duration = std::time::Duration::from_secs_f64(
                    (prev_position - original_trajectory_point.positions[joint_index]).abs()
                        / self.velocity_limits[joint_index],
                );
                limited_duration_from_prev = if single_duration > limited_duration_from_prev {
                    dominant_joint_index = joint_index;
                    single_duration
                } else {
                    limited_duration_from_prev
                }
            }
            let original_duration_from_prev =
                original_trajectory_point.time_from_start - original_duration_from_start;
            original_duration_from_start = original_trajectory_point.time_from_start;

            let use_limited = limited_duration_from_prev > original_duration_from_prev;
            let selected_duration = if use_limited {
                limited_duration_from_prev
            } else {
                original_duration_from_prev
            };
            limited_duration_from_start += selected_duration;
            limited_trajectory.push(TrajectoryPoint {
                positions: original_trajectory_point.positions.clone(),
                velocities: original_trajectory_point.velocities.clone(),
                time_from_start: limited_duration_from_start,
            });
            prev_positions.clone_from(&original_trajectory_point.positions);
            debug!(
                "Sequence{sequence_index} dominant joint_index {dominant_joint_index} duration limited : {limited_duration_from_prev:?}{} original : {original_duration_from_prev:?}{}",
                if use_limited { "(O)" } else { "" },
                if use_limited { "" } else { "(O)" }
            );
        }

        debug!("OriginalTrajectory {trajectory:?}");
        debug!("LimitedTrajectory {limited_trajectory:?}");

        self.client.send_joint_trajectory(limited_trajectory)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use assert_approx_eq::assert_approx_eq;

    use super::*;
    use crate::DummyJointTrajectoryClient;
    #[test]
    #[should_panic]
    fn mismatch_size() {
        let client = DummyJointTrajectoryClient::new(vec!["a".to_owned()]);
        JointVelocityLimiter::new(client, vec![1.0, 2.0]);
    }
    #[test]
    fn joint_names() {
        let client = DummyJointTrajectoryClient::new(vec!["a".to_owned(), "b".to_owned()]);
        let limiter = JointVelocityLimiter::new(client, vec![1.0, 2.0]);
        let joint_names = limiter.joint_names();
        assert_eq!(joint_names.len(), 2);
        assert_eq!(joint_names[0], "a");
        assert_eq!(joint_names[1], "b");
    }
    fn test_send_joint_positions(limits: Vec<f64>, expected_duration_secs: f64) {
        let client = Arc::new(DummyJointTrajectoryClient::new(vec![
            "a".to_owned(),
            "b".to_owned(),
        ]));
        let limiter = JointVelocityLimiter::new(client.clone(), limits);
        assert!(tokio_test::block_on(
            limiter
                .send_joint_positions(vec![1.0, 2.0], std::time::Duration::from_secs_f64(4.0))
                .unwrap()
        )
        .is_ok());
        let joint_positions = limiter.current_joint_positions().unwrap();
        assert_eq!(joint_positions.len(), 2);
        assert_approx_eq!(joint_positions[0], 1.0);
        assert_approx_eq!(joint_positions[1], 2.0);
        let trajectory = client.last_trajectory.lock().unwrap();
        assert_eq!(trajectory.len(), 1);
        assert_eq!(trajectory[0].positions.len(), 2);
        assert_approx_eq!(trajectory[0].positions[0], 1.0);
        assert_approx_eq!(trajectory[0].positions[1], 2.0);
        assert!(trajectory[0].velocities.is_none());
        assert_approx_eq!(
            trajectory[0].time_from_start.as_secs_f64(),
            expected_duration_secs
        );
    }

    #[test]
    fn send_joint_positions_none_limited() {
        test_send_joint_positions(vec![1.0, 2.0], 4.0);
    }

    #[test]
    fn send_joint_positions_limited() {
        // joint0 is over limit
        test_send_joint_positions(vec![0.1, 2.0], 10.0);
        // joint1 is over limit
        test_send_joint_positions(vec![1.0, 0.2], 10.0);
        // joint0/1 are over limit, joint0 is dominant
        test_send_joint_positions(vec![0.1, 0.6], 10.0);
        // joint0/1 are over limit, joint1 is dominant
        test_send_joint_positions(vec![0.3, 0.2], 10.0);
    }

    fn test_send_joint_trajectory(limits: Vec<f64>, expected_durations_secs: [f64; 2]) {
        let client = Arc::new(DummyJointTrajectoryClient::new(vec![
            "a".to_owned(),
            "b".to_owned(),
        ]));
        let limiter = JointVelocityLimiter::new(client.clone(), limits);
        assert!(tokio_test::block_on(
            limiter
                .send_joint_trajectory(vec![
                    TrajectoryPoint {
                        positions: vec![1.0, 2.0],
                        velocities: Some(vec![3.0, 4.0]),
                        time_from_start: std::time::Duration::from_secs_f64(4.0)
                    },
                    TrajectoryPoint {
                        positions: vec![3.0, 6.0],
                        velocities: Some(vec![3.0, 4.0]),
                        time_from_start: std::time::Duration::from_secs_f64(8.0)
                    }
                ])
                .unwrap()
        )
        .is_ok());
        let joint_positions = limiter.current_joint_positions().unwrap();
        assert_eq!(joint_positions.len(), 2);
        assert_approx_eq!(joint_positions[0], 3.0);
        assert_approx_eq!(joint_positions[1], 6.0);

        let trajectory = client.last_trajectory.lock().unwrap();
        assert_eq!(trajectory.len(), 2);
        assert_eq!(trajectory[0].positions.len(), 2);
        assert_approx_eq!(trajectory[0].positions[0], 1.0);
        assert_approx_eq!(trajectory[0].positions[1], 2.0);
        assert!(trajectory[0].velocities.is_some());
        assert_approx_eq!(trajectory[0].velocities.as_ref().unwrap()[0], 3.0);
        assert_approx_eq!(trajectory[0].velocities.as_ref().unwrap()[1], 4.0);

        assert_eq!(trajectory[1].positions.len(), 2);
        assert_approx_eq!(trajectory[1].positions[0], 3.0);
        assert_approx_eq!(trajectory[1].positions[1], 6.0);
        assert!(trajectory[1].velocities.is_some());
        assert_approx_eq!(trajectory[1].velocities.as_ref().unwrap()[0], 3.0);
        assert_approx_eq!(trajectory[1].velocities.as_ref().unwrap()[1], 4.0);

        assert_approx_eq!(
            trajectory[0].time_from_start.as_secs_f64(),
            expected_durations_secs[0]
        );

        assert_approx_eq!(
            trajectory[1].time_from_start.as_secs_f64(),
            expected_durations_secs[1]
        );
    }

    #[test]
    fn send_joint_trajectory_none_limited() {
        test_send_joint_trajectory(vec![1.0, 2.0], [4.0, 8.0]);
    }

    #[test]
    fn send_joint_trajectory_limited() {
        // joint0 is over limit
        test_send_joint_trajectory(vec![0.1, 2.0], [10.0, 30.0]);
        // joint1 is over limit
        test_send_joint_trajectory(vec![1.0, 0.2], [10.0, 30.0]);
        // joint0/1 are over limit, joint0 is dominant
        test_send_joint_trajectory(vec![0.1, 0.6], [10.0, 30.0]);
        // joint0/1 are over limit, joint1 is dominant
        test_send_joint_trajectory(vec![0.3, 0.2], [10.0, 30.0]);
        // joint0 / point1 is over limit
        test_send_joint_trajectory(vec![0.3, 2.0], [4.0, 4.0 + 2.0 / 0.3]);
        // joint1 / point1 is over limit
        test_send_joint_trajectory(vec![1.0, 0.8], [4.0, 4.0 + 4.0 / 0.8]);
    }

    #[test]
    fn from_urdf() {
        let s = r#"
            <robot name="robot">
                <joint name="a" type="revolute">
                    <origin xyz="0.0 0.0 0.0" />
                    <parent link="b" />
                    <child link="c" />
                    <axis xyz="0 1 0" />
                    <limit lower="-2" upper="1.0" effort="0" velocity="1.0"/>
                </joint>
            </robot>
        "#;
        let urdf_robot = urdf_rs::read_from_string(s).unwrap();
        let client = DummyJointTrajectoryClient::new(vec!["a".to_owned()]);
        let limiter = JointVelocityLimiter::from_urdf(client, &urdf_robot.joints).unwrap();
        assert_approx_eq!(limiter.velocity_limits[0], 1.0);

        // joint name mismatch
        let urdf_robot = urdf_rs::read_from_string(s).unwrap();
        let client = DummyJointTrajectoryClient::new(vec!["unknown".to_owned()]);
        let e = JointVelocityLimiter::from_urdf(client, &urdf_robot.joints)
            .err()
            .unwrap();
        assert!(matches!(e, Error::NoJoint(..)));
    }
}